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.
我的初始想法
int lengthOfLongestSubstring(string s) {
int index[128];
int len=s.length();
int str_len=0;
int start=0;
memset(index,0,128*4);
int tmp=0;
for(int i=0;i<len;i++){
if(index[s[i]]){
str_len=str_len>tmp?str_len:tmp;
tmp-=1;
}
index[s[i]]=1;
tmp+=1;
}
str_len=str_len>tmp?str_len:tmp;
return str_len;
}
这样的话,程序只实现了求String中不同字符的数目,继续加油ing~
Wrong answer之后的改进
引进了一个新的数组,location,标记元素的位置;以及每次重置的开始位置start
int lengthOfLongestSubstring(string s) {
int index[128];
memset(index,0,128*4);
int location[128];
int len=s.length();
int str_len=0;
int tmp=0;
int start=-1;
for(int i=0;i<len;i++){
if(index[s[i]]){
str_len=str_len>tmp?str_len:tmp;
for(int j=start+1; j<=location[s[i]]; j++)
index[s[j]]=0;
start=location[s[i]];
tmp=i-location[s[i]]-1;
}
location[s[i]]=i;
index[s[i]]=1;
tmp+=1;
}
str_len=str_len>tmp?str_len:tmp;
return str_len;
}
看了答案之后发现,我目前的思路是正确的,只是滑动窗口用的太死板,一个机智的用法可以减少time complexity到O(n);
int lengthOfLongestSubstring(string s) {
int index[128];
memset(index,0,128*4);
int len=s.length();
int str_len=0;
int start=0;
int i=0;
while(i<len){
if(index[s[i]]){
index[s[start++]]=0;
}
else{
index[s[i++]]=1;
}
str_len=str_len>i-start?str_len:i-start;
}
return str_len;
}
算法的世界果然太奇妙了,我估计还是一个在门外徘徊的门外汉吧~