Skip to content

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

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

    for (const char c : s)
      ans += ++count[c - 'a'];

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

    for (final char c : s.toCharArray())
      ans += ++count[c - 'a'];

    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