2083. Substrings That Begin and End With the Same Letter ¶ Time: $O(n)$ Space: $O(26) = O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class 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 11class 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 10class 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