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.
思路:用一个大小为128的int数组,0代表这个符号没有出现,1代表出现了,从字符串头开始读起,把每个字符用对应的ascall码装填到数组里,当发现当前字符已经存在,寻找该字符在该字符串第一次出现的位置,把字符串头到该位置之间的子串删除,从该位置的下一位重新开始读,直到字符串的结尾。
该思路的时间复杂度是O(n^2),需要128*sizeof(int)的空间
int lengthOfLongestSubstring(string s) {
int appear[127] = {0};
int flag = 0;
int max = 0, current = 0;
while(flag != s.size()){
if(appear[s[flag] ] == 1){
if(max < current) max = current;
current = 0;
memset(appear, 0, 127*sizeof(int));
int cut = s.find(s[flag]);
s.erase(0, cut+1);
flag = 0;
}
else{
appear[s[flag]] = 1;
current ++;
flag++;
}
}
if(max < current) max = current;
return max;
}