Skip to content

3090. Maximum Length Substring With Two Occurrences 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maximumLengthSubstring(string s) {
    int ans = 0;
    vector<int> count(26);

    for (int l = 0, r = 0; r < s.length(); ++r) {
      ++count[s[r] - 'a'];
      while (count[s[r] - 'a'] > 2)
        --count[s[l++] - 'a'];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maximumLengthSubstring(String s) {
    int ans = 0;
    int[] count = new int[26];

    for (int l = 0, r = 0; r < s.length(); ++r) {
      ++count[s.charAt(r) - 'a'];
      while (count[s.charAt(r) - 'a'] > 2)
        --count[s.charAt(l++) - 'a'];
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maximumLengthSubstring(self, s: str) -> int:
    ans = 0
    count = collections.Counter()

    l = 0
    for r, c in enumerate(s):
      count[c] += 1
      while count[c] > 2:
        count[s[l]] -= 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans