双指针做法,快慢指针,第一个走的快,发现有重复字符之后,第二个指针开始走
统计无重复字符可以用hash表或者set, 但是前者复杂度相对低一些
unordered_map版本
class Solution {public:int lengthOfLongestSubstring(string s) {unordered_map<char,int> hash;int res = 0;string ress = "";for(int l=0,r=0;r<s.length();r++){hash[s[r]]++;while(hash[s[r]]>1) hash[s[l++]]--;// 顺便统计一下最长子串if(r-l+1>res) ress = s.substr(l,r-l+1);res = max(res,r-l+1);}cout << ress << endl;return res;}};
set版本
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<int> lookup;
int left = 0, right,res = 0, n = s.length();
for(right=0;right<n;right++){
while(lookup.find(s[right])!=lookup.end()){
lookup.erase(s[left]);
left++;
}
res = max(res,right-left+1);
lookup.insert(s[right]);
}
return res;
}
};
