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

SQL关联表更新

看图识字,DELL SC4020 / SCv2000 控制器更换过程

What is next-generation modeling (with learning materials)

刘润直播预告 | 顶级高手,如何创造财富

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

leetcode经典例题——单词拆分

KT148A语音芯片ic工作原理以及芯片的内部架构描述

Essential knowledge for entry-level 3D game modelers

建模师经验分享:模型学习方法

QSunSync 七牛云文件同步工具,批量上传
随机推荐
jenkins发送邮件系统配置
性能测试如何准备测试数据
大师教你3D实时角色制作流程,游戏建模流程分享
软件测试面试题:软件验收测试的合格通过准则?
MongoDB permission verification is turned on and mongoose database configuration
TinyMCE禁用转义
电赛必备技能___定时ADC+DMA+串口通信
ARC129E Yet Another Minimization 题解 【网络流笔记】
软件质量评估的通用模型
软件测试面试题:做好测试计划的关键是什么?
再肝3天,整理了90个 NumPy 例子,不能不收藏!
After another 3 days, I have sorted out 90 NumPy examples, and I can't help but bookmark it!
Detailed explanation of common DNS resource record types
倒计时1天!8月2日—4日与你聊聊开源与就业那些事!
电子行业MES管理系统的主要功能与用途
leetcode经典例题——单词拆分
GO中sync包自由控制并发的方法
标识符、关键字、常量 和变量(C语言)
怎样进行在不改变主线程执行的时候,进行日志的记录
Cython