当前位置:网站首页>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;
}
};
边栏推荐
- MVCC是什么
- 网站最终产品页使用单一入口还是多入口?
- 00、数组及字符串常用的 API(详细剖析)
- 工业物联网 —— 新型数据库的召唤
- 【云原生--Kubernetes】调度约束
- After another 3 days, I have sorted out 90 NumPy examples, and I can't help but bookmark it!
- 电子行业MES管理系统的主要功能与用途
- 头脑风暴:完全背包
- 看图识字,DELL SC4020 / SCv2000 控制器更换过程
- uniapp sharing function - share to friends group chat circle of friends effect (sorting)
猜你喜欢
随机推荐
#yyds干货盘点#交换设备丢包严重的故障处理
Three tips for you to successfully get started with 3D modeling
"Relish Podcast" #397 The factory manager is here: How to use technology to empower the law?
【数据挖掘概论】数据挖掘的简单描述
怎么将自己新文章自动推送给自己的粉丝(巨简单,学不会来打我)
建模师经验分享:模型学习方法
【无标题】
[CVA Valuation Training Camp] Financial Modeling Guide - Lecture 1
Brainstorm: Complete Backpack
Mysql_12 多表查询
手写分布式配置中心(1)
KT148A语音芯片ic工作原理以及芯片的内部架构描述
三大技巧让你成功入门3D建模,零基础小白必看
Cython
[LeetCode] Summary of Matrix Simulation Related Topics
Privacy Computing Overview
SQL关联表更新
软件质量评估的通用模型
golang 协程的实现原理
大师教你3D实时角色制作流程,游戏建模流程分享








