Skip to main content

Substrings That Begin and End With the Same Letter

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 76 ms)​

MetricValue
Runtime76 ms
Memory40.7 MB
Date2021-12-29
Solution
public class Solution {
public long NumberOfSubstrings(string s) {
long n = s.Length;
long count = 0;
long[] occurences = new long[26];
for (int i = 0; i < n; i++)
{
occurences[s[i] - 'a'] += 1;
}
for (int i = 0; i < 26; i++)
{
count += occurences[i] > 0 ? (occurences[i] * (occurences[i] + 1)) / 2 : 0;
}

return count;
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed