美文网首页
159. Longest Substring with At M

159. Longest Substring with At M

作者: 怪味儿果叔 | 来源:发表于2017-01-05 12:15 被阅读0次

    Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
    For example, Given s = “eceba”, T is "ece" which its length is 3.


    Task is that we should find the longest substring which only has two characters but get the two appear as many times as possible.

    First Thought

    The most important idea in solving this kind of questions is "how to update the "start" pointer".

    int lengthOfLongestSubstringTwoDistinct(string s) {
      if(s.length() <= 2) return s.length();
      vector<int> dict(256, -1);
      int count = 0, maxLength = 0, start = 0;
      char prev;
      for(int i = 0; i < s.length(); i++){
        if(prev != s[i]){ //chars not the same as the current one
          if(count < 2){ // found new chars in substr
            count++;
            dict[s[i]] = i;
            maxLength = max(maxLength, i-start+1);
          }else if(count == 2 && dict[s[i]] >= 0){ // char already exist in substr
            dict[s[i]] = i;
            maxLength = max(maxLength, i-start+1);
          }else if(dict[s[i]] < 0){ // third char
            maxLength = max(maxLength, i-start);
            start = dict[prev];
            dict[s[dict[prev]-1]] = -1;
            dict[s[i]] = i;
          }
          prev = s[i];
        }else{
          maxLength = max(maxLength, i-start+1);
        }
      }
      return maxLength;
    }
    

    Second Solution

    Two Pointers. Still O(N), but hard to extend to k distinct characters substring.

    int lengthOfLongestSubstringTwoDistinct(string s){
      int first = 0, second = -1;
      int maxLength = 0;
      for(int i = 1; i < s.length(); i++){
        if(s[i-1] == s[i]) continue;
        if(second > -1 && s[i] != s[second]){
          maxLength = max(maxLength, i-first);
          first = second+1;
        }
        second = i - 1;
      }
      return maxLength > (s.size() - first) ? maxLength : s.size() - first;
    }
    

    相关文章

      网友评论

          本文标题:159. Longest Substring with At M

          本文链接:https://www.haomeiwen.com/subject/opeovttx.html