双指针做法,快慢指针,第一个走的快,发现有重复字符之后,第二个指针开始走
统计无重复字符可以用hash表或者set, 但是前者复杂度相对低一些

unordered_map版本

  1. class Solution {
  2. public:
  3. int lengthOfLongestSubstring(string s) {
  4. unordered_map<char,int> hash;
  5. int res = 0;
  6. string ress = "";
  7. for(int l=0,r=0;r<s.length();r++){
  8. hash[s[r]]++;
  9. while(hash[s[r]]>1) hash[s[l++]]--;
  10. // 顺便统计一下最长子串
  11. if(r-l+1>res) ress = s.substr(l,r-l+1);
  12. res = max(res,r-l+1);
  13. }
  14. cout << ress << endl;
  15. return res;
  16. }
  17. };

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;
    }
};