3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
巧妙地方在于p[s[i]]>start的判断;
当小于start时,表明是初次遇到,当大于时,表明不是初次遇见,即要将此字符的第一次见面地点作为起点。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len=s.length(),len_max=0,start=-1,p[128];
for(int i=0;i<128;i++)p[i]=-1;
for(int i=0;i<len;i++){
if(p[s[i]]>start)
start=p[s[i]];
p[s[i]]=i;
len_max=max(len_max,i-start);
}
return len_max;
}
};