当前位置:网站首页>leetcode:266. 回文全排列
leetcode:266. 回文全排列
2022-08-05 00:10:00 【OceanStar的学习笔记】
题目来源
题目描述
给定一个字符串,判断该字符串中是否可以通过重新排列组合,形成一个回文字符串。
题目解析
思路
回文序列:
- 如果字符串的长度是奇数长度时,只有一个字母出现的次数是奇数,其余均为偶数
- 如果字符串的长度是奇偶长度时,每个字母出现的次数一定是偶数次
实现
同一个map来统计
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> m;
int cnt = 0;
for (auto a : s) ++m[a];
for (auto a : m) {
if (a.second % 2 == 1) ++cnt;
}
return cnt == 0 || (s.size() % 2 == 1 && cnt == 1);
}
};
用set也可以
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_set<char> st;
for (auto a : s) {
if (!st.count(a)) st.insert(a);
else st.erase(a);
}
return st.empty() || st.size() == 1;
}
};
bitset
- 建立一个 256 大小的 bitset,每个字母根据其 ASCII 码值的不同都有其对应的位置
- 然后我们遍历整个字符串,遇到一个字符,就将其对应的位置的二进制数 flip 一下,就是0变1,1变0
- 那么遍历完成后,所有出现次数为偶数的对应位置还应该为0,而出现次数为奇数的时候,对应位置就为1了
- 也就是说我们最后只要统计1的个数,就知道出现次数为奇数的字母的个数了,只要个数小于2就是回文数
class Solution {
public:
bool canPermutePalindrome(string s) {
bitset<256> b;
for (auto a : s) {
b.flip(a);
}
return b.count() < 2;
}
};
边栏推荐
猜你喜欢

Xiaohei's leetcode journey: 95. Longest substring with at least K repeating characters

what?测试/开发程序员要被淘汰了?年龄40被砍到了32?一瞬间,有点缓不过神来......

【LeetCode】双指针题解汇总

10 种常见的BUG分类

矩阵数学原理

软件开发工具的技术要素

Flutter启动流程(Skia引擎)介绍与使用

Essential knowledge for entry-level 3D game modelers

学会反射后,我被录取了(干货)

【Valentine's Day special effects】--Canvas realizes full screen love
随机推荐
The role of the annotation @ EnableAutoConfiguration and how to use
电子行业MES管理系统的主要功能与用途
#yyds干货盘点#交换设备丢包严重的故障处理
Brainstorm: Complete Backpack
情侣牵手[贪心 & 抽象]
头脑风暴:完全背包
《MySQL入门很轻松》第2章:MySQL管理工具介绍
lua 如何 实现一个unity协程的工具
VMware NSX 4.0 -- 网络安全虚拟化平台
【LeetCode】图解 904. 水果成篮
学会反射后,我被录取了(干货)
SQL association table update
KT148A语音芯片怎么烧录语音进入芯片里面通过串口和电脑端的工具
Flutter启动流程(Skia引擎)介绍与使用
【数据挖掘概论】数据挖掘的简单描述
The master teaches you the 3D real-time character production process, the game modeling process sharing
2022牛客暑期多校训练营5(BCDFGHK)
Mysql_13 事务
工业物联网 —— 新型数据库的召唤
.net(C#)获取两个日期间隔的年月日