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:

  1. Initialize a variable result to store the final sum of unique characters.
  2. Iterate through all possible substrings of the given string.
  3. For each substring, calculate the number of unique characters using a HashSet to store the characters.
  4. Add the count of unique characters in each substring to the result.
  5. 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;
    }
}

Loading editor...