题目:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
Tags Hash Table Two Pointers String
Similar Problems (H) Longest Substring with At Most Two Distinct Characters
分析:
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
static int CSPECNUM = 256;
int repos[CSPECNUM];
for(int i=0;i<CSPECNUM;i++)
repos[i] = -1;
int max = 0;
int strSize = s.size();
int start = 0;
int len = 0;
for(int i=0;i<strSize;i++)
{
if( repos[s[i]] >= start )
start = repos[s[i]] + 1;
len = i - start + 1;
if(len>max)
max = len;
repos[s[i]] = i;
}
return max;
}
};
结果:
总结:
学会分析数据内在规律,节省运行时间。