前缀和+哈希表,LeetCode 1915. 最美子字符串的数目

一、题目

1、题目描述

如果某个字符串中 至多一个 字母出现 奇数 次,则称其为 最美 字符串。

  • 例如,"ccjjc" 和 "abab" 都是最美字符串,但 "ab" 不是。

给你一个字符串 word ,该字符串由前十个小写英文字母组成('a' 到 'j')。请你返回 word 中 最美非空子字符串 的数目*。* 如果同样的子字符串在word 中出现多次,那么应当对 每次出现 分别计数*。*

子字符串 是字符串中的一个连续字符序列。

2、接口描述

python3
复制代码
 ​
python 复制代码
class Solution:
    def wonderfulSubstrings(self, word: str) -> int:
        n = len(word)

        cnt = Counter()
        cnt[0] = 1
        res = s = 0
                
        for i, x in enumerate(word):
            s ^= 1 << (ord(x) - ord('a'))
            res += cnt[s] # 全偶
            res += sum(cnt[s ^ (1 << y)] for y in range(10))
            cnt[s] += 1

        return res

3、原题链接

1915. Number of Wonderful Substrings


二、解题报告

1、思路分析

考虑用10个二进制位表示当前前缀每个字符出现的奇偶性

那么si, j 合法,一定满足acci - 1 ^ accj 最多只有一个二进制位为1

我们用哈希表记录每个前缀异或和出现次数,边维护前缀异或和边计数即可

计数来自两部分:(记当前前缀异或和为s)

全为偶数:那么区间异或和为0,贡献就是cnts

只有一个1:那么枚举是1的位,贡献就是cnts \^ (1 \<\< j)

2、复杂度

时间复杂度: O(N)空间复杂度:O(N)

3、代码详解

python3
python 复制代码
class Solution:
    def wonderfulSubstrings(self, word: str) -> int:
        n = len(word)

        cnt = Counter()
        cnt[0] = 1
        res = s = 0
                
        for i, x in enumerate(word):
            s ^= 1 << (ord(x) - ord('a'))
            res += cnt[s] # 全偶
            res += sum(cnt[s ^ (1 << y)] for y in range(10))
            cnt[s] += 1

        return res
复制代码
 ​
相关推荐
Navigator_Z9 分钟前
LeetCode //C - 1304. Find N Unique Integers Sum up to Zero
c语言·算法·leetcode
BK贝壳9 小时前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节
?abc!12 小时前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
hold?fish:palm15 小时前
40 二叉树的直径
c++·leetcode
guo_wen_qiang16 小时前
二叉树的层序遍历-使用双端队列Deque
算法·leetcode·1024程序员节
爱读书的小胖16 小时前
LeetCode 55 跳跃游戏 C 语言解题分析
c语言·数据结构·算法·leetcode·1024程序员节
舰长11516 小时前
将百万数据插入到 Redis,有哪些实现方案?
数据结构·redis·开源
Navigator_Z17 小时前
LeetCode //C - 1300. Sum of Mutated Array Closest to Target
c语言·算法·leetcode
若亦_18 小时前
数据结构>>优先级队列(堆)
java·数据结构
凯瑟琳.奥古斯特18 小时前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展