Skip to content

2743. Count Substrings Without Repeating Character 👍

  • 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 numberOfSpecialSubstrings(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 += r - l + 1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int numberOfSpecialSubstrings(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 += r - l + 1;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def numberOfSpecialSubstrings(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 += r - l + 1

    return ans