前缀和+哈希表,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个二进制位表示当前前缀每个字符出现的奇偶性

那么s[i, j] 合法,一定满足acc[i - 1] ^ acc[j] 最多只有一个二进制位为1

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

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

全为偶数:那么区间异或和为0,贡献就是cnt[s]

只有一个1:那么枚举是1的位,贡献就是cnt[s ^ (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
复制代码
 ​
相关推荐
Learner__Q25 分钟前
每天五分钟:滑动窗口-LeetCode高频题解析_day3
python·算法·leetcode
阿昭L39 分钟前
leetcode链表相交
算法·leetcode·链表
小南家的青蛙2 小时前
LeetCode第1261题 - 在受污染的二叉树中查找元素
算法·leetcode·职场和发展
玖剹3 小时前
记忆化搜索题目(二)
c语言·c++·算法·leetcode·深度优先·剪枝·深度优先遍历
Jul1en_4 小时前
【算法】分治-归并类题目
java·算法·leetcode·排序算法
java修仙传4 小时前
力扣hot100:寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
xiaolang_8616_wjl6 小时前
c++超级细致的基本框架
开发语言·数据结构·c++·算法
F_D_Z6 小时前
哈希表解Two Sum问题
python·算法·leetcode·哈希表
LYFlied7 小时前
【每日算法】LeetCode124. 二叉树中的最大路径和
数据结构·算法·leetcode·面试·职场和发展
yyy(十一月限定版)8 小时前
c语言——栈和队列
java·开发语言·数据结构