1915. Number of Wonderful Substrings
Description
A wonderful string is a string where at most one letter appears an odd number of times.
- For example,
"ccjjc"and"abab"are wonderful, but"ab"is not.
Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.
A substring is a contiguous sequence of characters in a string.
Β
Example 1:
Input: word = "aba" Output: 4 Explanation: The four wonderful substrings are underlined below: - "aba" -> "a" - "aba" -> "b" - "aba" -> "a" - "aba" -> "aba"
Example 2:
Input: word = "aabb" Output: 9 Explanation: The nine wonderful substrings are underlined below: - "aabb" -> "a" - "aabb" -> "aa" - "aabb" -> "aab" - "aabb" -> "aabb" - "aabb" -> "a" - "aabb" -> "abb" - "aabb" -> "b" - "aabb" -> "bb" - "aabb" -> "b"
Example 3:
Input: word = "he" Output: 2 Explanation: The two wonderful substrings are underlined below: - "he" -> "h" - "he" -> "e"
Β
Constraints:
1 <= word.length <= 105wordconsists of lowercase English letters from'a'Β to'j'.
Solutions
Solution 1: Prefix XOR + Counting
Since the string contains only \(10\) lowercase letters, we can use a \(10\)-bit integer to represent the parity of each letter count in the current prefix. The \(i\)-th bit is \(1\) if the \(i\)-th letter appears an odd number of times, and \(0\) if it appears an even number of times.
We iterate through each character in the string. Use a variable \(st\) to maintain the current prefix XOR state, and an array \(cnt\) to record how many times each prefix state has appeared. Initially, \(st = 0\) and \(cnt[0] = 1\).
For each character, update the prefix XOR state. If the current state has appeared \(cnt[st]\) times, it means there are \(cnt[st]\) substrings in which all letter counts are even, so we add \(cnt[st]\) to the answer. In addition, for \(0 \le i < 10\), toggling the \(i\)-th bit of \(st\) (i.e., \(st \oplus (1 << i)\)) represents substrings where exactly one letter has an odd count, so we add \(cnt[st \oplus (1 << i)]\) to the answer. Finally, increment the occurrence count of \(st\) by \(1\), and continue.
The time complexity is \(O(n \times \Sigma)\), and the space complexity is \(O(2^{\Sigma})\), where \(\Sigma = 10\) and \(n\) is the length of the string.
Similar problems:
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |