问题描述
Given a string, find the length of the longest substring without repeating characters.
(找出最长的没有重复字母出现的子串。输出其最长长度。)
例子
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.
思路
- 有一个结论只要重复出现,index之前的东西就失去了作用,只用记录index之后的字符。
- 如果不是重复字符, index==-1 ,那么就让max++;
- 如果不是重复字符,index!=-1,就比较记录max。不能直接max++,也不能直接max=i-index; 例如:abcaad
- 如果出现重复,并且是在index之后出现,给记录,再比较max
- 如果出现重复,在index之前出现,比较记录max
测试用例
"abcabcss" 4
"aaaaa" 1
"qwwwejw" 3
"abcade" 5
"abba" 2 index之前的就不算了
"ohomm" 3
"tmmzuxt" 5 因为t出现过,所以return的判断还是有必要的
"alouzxilkaxkufsu" 8
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int index = -1; //每遇到重复值,就记录下其第一次出现的下标
int max = 0, len = s.size(); //max记录当前最长
int mapping[200] = {0};
int val; // 记录字符
for(int i = 0; i < len; i ++){
val = s[i];
//如果出现过,并且是在index之后出现,给记录
if(mapping[val]>0){
if(index <= mapping[val]-1){
index = mapping[val]-1;
}
max = max>=i-index?max:i-index;
}
//if(index==-1) max++;
//
if(mapping[val]<=0) {
if(index==-1) max++;
else{
max = max>=i-index?max:i-index;
}
}
cout<<index<<" "<<max<<" "<<val<<endl;
mapping[val] = i+1;
}
if(index == -1) return max;
else return max>=len-index-1?max:len-index-1;
}
};
//改进版
int lengthOfLongestSubstring(string s) {
int index = 0; //每遇到重复值,就记录下其第一次出现的下标
int max = 0, len = s.size(); //max记录当前最长
int mapping[200] = {0};
int val; // 记录字符
for(int i = 0; i < len; i ++){
val = s[i];
index = mapping[val]>index?mapping[val]:index;
max = max>i-index+1?max:i-index+1;
mapping[val] = i+1;
}
return max;
}
补充
ASCII码
'a' 97 'A' 65 '0' 48
'z' 122 'Z' 90 '9' 57