LeetCode题解(1542):找出最长的可通过字符交换转变为回文串的子字符串(Python)
发布日期:2021-06-29 19:58:53 浏览次数:2 分类:技术文章

本文共 1587 字,大约阅读时间需要 5 分钟。

题目:(困难)

标签:字符串、哈希表、位运算

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N ) O(N) O(N) O ( N ) O(N) O(N) 1908ms (35.27%)
Ans 2 (Python) O ( N ) O(N) O(N) O ( N ) O(N) O(N) 320ms (97.10%)
Ans 3 (Python)

解法一(哈希表):

class Solution:    def longestAwesome(self, s: str) -> int:        ans = 0        now = 0  # 当前各个数字的奇偶状态        hashmap = {
now: 0} # 每个奇偶状态的最早出现坐标 for i, ch in enumerate(s): # 计算当前数字添加后奇偶状态的变化 now ^= 1 << int(ch) if now not in hashmap: hashmap[now] = i + 1 # 计算当前奇偶状态构成回文串的最早坐标 if now in hashmap: ans = max(ans, i - hashmap[now] + 1) for j in range(10): tmp = now ^ (1 << j) if tmp in hashmap: ans = max(ans, i - hashmap[tmp] + 1) # print(i, "[", ch, "]", bin(now)[2:], "->", ans) return ans

解法二(优化解法一):

class Solution:    def longestAwesome(self, s: str) -> int:        status = 0  # 当前各个数字的奇偶状态        hashmap = {
status: [0, 0]} # 每个奇偶状态的最早出现坐标 for i, ch in enumerate(s): # 计算当前数字添加后奇偶状态的变化 status ^= 1 << int(ch) if status not in hashmap: hashmap[status] = [i + 1, i + 1] else: hashmap[status][1] = i + 1 # 计算当前奇偶状态构成回文串的最早坐标 ans = 1 for status in hashmap: ans = max(ans, hashmap[status][1] - hashmap[status][0]) for j in range(10): if (tmp := status ^ (1 << j)) in hashmap: ans = max(ans, hashmap[status][1] - hashmap[tmp][0]) return ans

转载地址:https://dataartist.blog.csdn.net/article/details/108357067 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(1544):移除字符串中连续的、相同字母的大写和小写字符(Python)
下一篇:LeetCode题解(1541):使字符串变为平衡括号字符串的最少插入次数(Python)

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月14日 21时02分32秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章