LeetCode 828: Count Unique Characters of All Substrings of a Given String
Problem Description
Explanation:
To solve this problem, we need to count the number of unique characters in all substrings of a given string. We can achieve this by iterating through all possible substrings and counting the unique characters in each substring.
Here is the algorithmic idea:
- Initialize a variable
result
to store the final sum of unique characters. - Iterate through all possible substrings of the given string.
- For each substring, calculate the number of unique characters using a HashSet to store the characters.
- Add the count of unique characters in each substring to the
result
. - Return the
result
as the final answer.
Time Complexity: O(n^2) where n is the length of the input string. Space Complexity: O(n) for the HashSet.
:
Solutions
class Solution {
public int uniqueLetterString(String s) {
int mod = 1000000007;
int result = 0;
for (int i = 0; i < s.length(); i++) {
int left = i, right = i;
while (left >= 0 && s.charAt(left) != s.charAt(i)) {
left--;
}
while (right < s.length() && s.charAt(right) != s.charAt(i)) {
right++;
}
result = (result + (i - left) * (right - i)) % mod;
}
return result;
}
}
Related LeetCode Problems
Loading editor...