LeetCode 3. Longest Substring Without Repeating Characters(C++),leetcoderepeating
分享于 点击 35985 次 点评:90
LeetCode 3. Longest Substring Without Repeating Characters(C++),leetcoderepeating
这道题我是强行调出来的,花了很长时间,大概思路是,使用map存储遍历的字符与字符位置(用于比较是否有重复字符),start和end标记符合条件的序列的开始位置和结束位置,如果遇到重复的字符,就移动start到end这,end+1,并清空map。从头到尾遍历字符串,在遍历过程中维护max为end-start的最大值,就得到题设的结果了。
感觉解的太麻烦了,肯定有更简洁的解法。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.length()==0 || s.length()==1)
return s.length();
int start = 0,end = 0;
int max = 0;
map<char,int>my_map;
while(end<=s.length()-1)
{
if(my_map.find(s[end])!=my_map.end())
{
start=my_map.find(s[end])->second+1;
// cout<<"find "<<s[end]<<" at "<<start-1<<endl;
max = max > end-start+1? max: end-start+1;
my_map.clear();
my_map[s[start]]=start;
// cout<<"insert pair "<<s[start]<<" "<<start<<endl;
end=start+1;
}else
{
my_map[s[end]]=end;
max = max > end-start+1? max: end-start+1;
end++;
}
// cout<<"max:"<<max<<" "<<end<<" "<<start<<endl;
}
return max;
}
};
相关文章
- 暂无相关文章
用户点评