当前位置:网站首页>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;
}
};
边栏推荐
- ARC129E Yet Another Minimization 题解 【网络流笔记】
- what is MVCC
- Senior game modelers tell newbies, what are the necessary software for game scene modelers?
- 软件测试面试题:做好测试计划的关键是什么?
- 2022 Niu Ke Summer Multi-School Training Camp 5 (BCDFGHK)
- 再肝3天,整理了90个 NumPy 例子,不能不收藏!
- 【LeetCode】双指针题解汇总
- MongoDB permission verification is turned on and mongoose database configuration
- leetcode:266. 回文全排列
- .net (C#) get year month day between two dates
猜你喜欢
随机推荐
数据类型-整型(C语言)
How to burn the KT148A voice chip into the chip through the serial port and the tools on the computer
Metasploit-域名上线隐藏IP
"Relish Podcast" #397 The factory manager is here: How to use technology to empower the law?
从单体架构迁移到 CQRS 后,我觉得 DDD 并不可怕
Mysql_14 存储引擎
网站最终产品页使用单一入口还是多入口?
三、实战---爬取百度指定词条所对应的结果页面(一个简单的页面采集器)
工业物联网 —— 新型数据库的召唤
【无标题】线程三连鞭之“线程池”
NMS原理及其代码实现
简单的顺序结构程序(C语言)
Ab3d.PowerToys and Ab3d.DXEngine Crack
gorm联表查询-实战
KT148A语音芯片怎么烧录语音进入芯片里面通过串口和电脑端的工具
IDEA file encoding modification
node使用redis
子连接中的参数传递
tiup update
D - I Hate Non-integer Number (选数的计数dp