Skip to content

1876. Substrings of Size Three with Distinct Characters 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int countGoodSubstrings(string s) {
    int ans = 0;

    for (int i = 0; i + 2 < s.length(); ++i) {
      const char a = s[i];
      const char b = s[i + 1];
      const char c = s[i + 2];
      if (a == b || a == c || b == c)
        continue;
      ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int countGoodSubstrings(String s) {
    int ans = 0;

    for (int i = 0; i < s.length() - 2; ++i) {
      final char a = s.charAt(i);
      final char b = s.charAt(i + 1);
      final char c = s.charAt(i + 2);
      if (a == b || a == c || b == c)
        continue;
      ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def countGoodSubstrings(self, s: str) -> int:
    ans = 0

    for a, b, c in zip(s, s[1:], s[2:]):
      if a == b or a == c or b == c:
        continue
      ans += 1

    return ans