LeetCode Solutions

828. Count Unique Characters of All Substrings of a Given String

Time:

Space:

			

class Solution {
 public:
  int uniqueLetterString(string s) {
    int ans = 0;
    int count = 0;
    vector<int> lastCount(26);
    vector<int> lastSeen(26, -1);

    for (int i = 0; i < s.length(); ++i) {
      const int c = s[i] - 'A';
      const int currentCount = i - lastSeen[c];
      count = count - lastCount[c] + currentCount;
      lastCount[c] = currentCount;
      lastSeen[c] = i;
      ans += count;
    }

    return ans;
  }
};
			

class Solution {
  public int uniqueLetterString(String s) {
    int ans = 0;
    int count = 0;
    int[] lastCount = new int[26];
    int[] lastSeen = new int[26];
    Arrays.fill(lastSeen, -1);

    for (int i = 0; i < s.length(); ++i) {
      final int c = s.charAt(i) - 'A';
      final int currentCount = i - lastSeen[c];
      count = count - lastCount[c] + currentCount;
      lastCount[c] = currentCount;
      lastSeen[c] = i;
      ans += count;
    }

    return ans;
  }
}
			

class Solution:
  def uniqueLetterString(self, s: str) -> int:
    ans = 0
    count = 0
    lastCount = [0] * 26
    lastSeen = [-1] * 26

    for i, c in enumerate(s):
      c = ord(c) - ord('A')
      currentCount = i - lastSeen[c]
      count = count - lastCount[c] + currentCount
      lastCount[c] = currentCount
      lastSeen[c] = i
      ans += count

    return ans