当前位置:网站首页>leetcode: 266. All Palindromic Permutations
leetcode: 266. All Palindromic Permutations
2022-08-05 00:20:00 【OceanStar's study notes】
题目来源
题目描述
给定一个字符串,判断该字符串中是否可以通过重新排列组合,形成一个回文字符串.
题目解析
思路
回文序列:
- If the length of the string is an odd length,Only one letter appears an odd number of times,其余均为偶数
- If the length of the string is parity length,The number of occurrences of each letter must be an even number
实现
同一个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 Different code values have their corresponding positions
- Then we iterate over the entire string,遇到一个字符,Just put the binary number of its corresponding position flip 一下,就是0变1,1变0
- Then after the traversal is complete,All corresponding positions with an even number of occurrences should also be 0,And when the number of occurrences is odd,对应位置就为1了
- That is to say, we only need statistics in the end1的个数,You know the number of letters with odd occurrences,as long as the number is less than2就是回文数
class Solution {
public:
bool canPermutePalindrome(string s) {
bitset<256> b;
for (auto a : s) {
b.flip(a);
}
return b.count() < 2;
}
};
边栏推荐
猜你喜欢

Implementation principle of golang coroutine
![[LeetCode] Summary of Matrix Simulation Related Topics](/img/80/bd71ca5211cce5805909015a642893.jpg)
[LeetCode] Summary of Matrix Simulation Related Topics

测试经理要不要做测试执行?

KT148A voice chip ic working principle and internal architecture description of the chip

What is next-generation modeling (with learning materials)

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

《MySQL入门很轻松》第2章:MySQL管理工具介绍

KT6368A Bluetooth certification problem_FCC and BQB_CE_KC certification or other instructions

Metasploit-域名上线隐藏IP
![情侣牵手[贪心 & 抽象]](/img/7d/1cafc000dc58f1c5e2e92150be7953.png)
情侣牵手[贪心 & 抽象]
随机推荐
阅读笔记:如何理解DevOps?
Mysql_12 多表查询
倒计时1天!8月2日—4日与你聊聊开源与就业那些事!
看图识字,DELL SC4020 / SCv2000 控制器更换过程
How to automatically push my new articles to my fans (very simple, can't learn to hit me)
一、爬虫基本概念
元宇宙:未来我们的每一个日常行为是否都能成为赚钱工具?
[Cloud Native--Kubernetes] Pod Controller
《MySQL入门很轻松》第2章:MySQL管理工具介绍
SV 类的虚方法 多态
gorm的Raw与scan
入门3D游戏建模师知识必备
How to burn the KT148A voice chip into the chip through the serial port and the tools on the computer
Metasploit-域名上线隐藏IP
2022 Niu Ke Summer Multi-School Training Camp 5 (BCDFGHK)
KT148A电子语音芯片ic方案适用的场景以及常见产品类型
Couple Holding Hands [Greedy & Abstract]
在线中文姓名生成工具推荐
Flask框架 根据源码分析可扩展点
对写作的一些感悟