LeetCode 1915. Number of Wonderful Substrings
原题链接在这里:https://leetcode.com/problems/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 <= 105
word
consists of lowercase English letters from'a'
to'j'
.
题解:
To count the number of fulfilling substrings, we need to maintain the prefix count.
Since the word only consist 'a' to 'j' that is 10 letters, then we can use a state of then diigts to note the previous state. each digit dentoes how many previous letter occurs % 2.
Then there could be 1 << 10 different states.
Use count to maintain all the state counts.
count[0] = 1 for no letter, the count is 1. Then later "aa" occurs, its state is "000000000", accumulate the count[0] to result.
Since it is at most one letter, there are two types.
One is all the even freq. res += count[state]. state are the same for this substring
The other is flip one letter. from a to j, try flip its corresponding index.
Time Complexity: O(n). n = word.length().
Space: O(1).
AC Java:
1 class Solution { 2 public long wonderfulSubstrings(String word) { 3 long[] count = new long[1 << 10]; 4 count[0] = 1; 5 int state = 0; 6 long res = 0; 7 int n = word.length(); 8 for(int i = 0; i < n; i++){ 9 int val = word.charAt(i) - 'a'; 10 state ^= (1 << val); // state[i] 11 res += count[state]; // all letter freq are even 12 for(int k = 0; k < 10; k++){ 13 int stateOdd = state ^ (1 << k); // flip one letter 14 res += count[stateOdd]; 15 } 16 17 count[state]++; 18 } 19 20 return res; 21 } 22 }