Skip to content

2083. Substrings That Begin and End With the Same Letter 👍

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

    for (const char c : s) {
      ans += count[c] + 1;
      ++count[c];
    }

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

    for (final char c : s.toCharArray()) {
      ans += count[c] + 1;
      ++count[c];
    }

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

    for c in s:
      ans += count[c] + 1
      count[c] += 1

    return ans