当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

什么是次世代建模(附学习资料)

2022牛客暑期多校训练营5(BCDFGHK)
情人节---快来学习一下程序员的专属浪漫吧

Statistical words (DAY 101) Huazhong University of Science and Technology postgraduate examination questions

Mathematical Principles of Matrix

怎么将自己新文章自动推送给自己的粉丝(巨简单,学不会来打我)

【LeetCode】图解 904. 水果成篮

机器学习(公式推导与代码实现)--sklearn机器学习库

uniapp sharing function - share to friends group chat circle of friends effect (sorting)

小黑leetcode之旅:95. 至少有 K 个重复字符的最长子串
随机推荐
LeetCode Hot 100
NebulaGraph v3.2.0 Release Note,对查询最短路径的性能等多处优化
uniapp动态实现滑动导航效果demo(整理)
10 个关于 Promise 和 setTimeout 知识的面试题,通过图解一次说透彻
软件开发工具的技术要素
RK3399平台开发系列讲解(内核调试篇)2.50、嵌入式产品启动速度优化
2022年华数杯数学建模
Develop a SpaceX website based on the Appian low-code platform
元宇宙:未来我们的每一个日常行为是否都能成为赚钱工具?
【论文笔记】—低照度图像增强—Unsupervised—EnlightenGAN—2019-TIP
关于使用read table 语句
从单体架构迁移到 CQRS 后,我觉得 DDD 并不可怕
Statistical words (DAY 101) Huazhong University of Science and Technology postgraduate examination questions
学会反射后,我被录取了(干货)
The master teaches you the 3D real-time character production process, the game modeling process sharing
After another 3 days, I have sorted out 90 NumPy examples, and I can't help but bookmark it!
入门3D游戏建模师知识必备
typeScript - Partially apply a function
看图识字,DELL SC4020 / SCv2000 控制器更换过程
Huggingface入门篇 II (QA)