当前位置:网站首页>【LeetCode】Day109-最长回文串
【LeetCode】Day109-最长回文串
2022-08-01 18:19:00 【倒过来是圈圈】
题目
题解
思路
回文串必须是对称的,那既然提到对称,就说明每个字母都需要出现偶数次,至多只有一个字母出现奇数次,且为1次(贪心思路)
算法
设字母ch出现v次,那么我们可以使用ch共 v / 2 ∗ 2 v/2*2 v/2∗2次,有任何一个字母出现奇数次,则可以把它作为回文串中心,中心最多仅有1个。
class Solution {
public int longestPalindrome(String s) {
int n=s.length();
//统计字符出现次数
int[] count=new int[128];
for(int i=0;i<n;i++){
char c=s.charAt(i);
count[c]++;
}
//最长回文串长度
int res=0;
for(int i='A';i<='z';i++){
res+=count[i]/2*2;
//奇数次且没有回文中心
if(count[i]%2==1&&res%2==0)
res++;
}
return res;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( S ) O(S) O(S),其中 S 为字符集大小
边栏推荐
- Clip-on multimeter use method, how to measure the voltage, current, resistance?
- 钳形万用表使用方法,如何测量电压、电流、电阻?
- 7月30号|来一场手把手助您打造智能视觉新爆款的技术动手实验
- MySQL 45 讲 | 09 普通索引和唯一索引,应该怎么选择?
- Live chat system technology (8) : vivo live IM message module architecture practice in the system
- University of California | Inverse Reinforcement Learning from Different Third-Person Videos via Graph Abstraction
- QT_QDialog 对话框
- Topology零部件拆解3D可视化解决方案
- AntDB database appeared in the 24th high-speed exhibition, helping smart high-speed innovative applications
- MySQL数据库————存储过程和函数
猜你喜欢
电商库存系统的防超卖和高并发扣减方案
QLineEdit学习与使用
How many steps does it take to convert an ENS domain name into music?
暑假第二周总结博客
【Day_11 0506】 最近公共祖先
粒子滤波 particle filter —从贝叶斯滤波到粒子滤波——Part-I(贝叶斯滤波)
What is the JVM runtime data area and the JMM memory model
XAML WPF项目groupBox控件
史上最全的Redis基础+进阶项目实战总结笔记
C#/VB.NET:从 PDF 文档中提取所有表格
随机推荐
opencv如何实现图像倾斜校正
解决MySQL插入不了中文数据问题
University of California | Inverse Reinforcement Learning from Different Third-Person Videos via Graph Abstraction
What is the JVM runtime data area and the JMM memory model
关于单应性矩阵的若干思考
opencv语法Mat类型总结
WinRAR | 将多个安装程序生成一个安装程序
Basic image processing in opencv
EpiSci|片上系统的深度强化学习:神话与现实
MySQL Lock wait timeout exceeded; try restarting transaction 锁等待
typora操作手册
QT commonly used global macro definitions
JVM运行时数据区与JMM内存模型是什么
7月30号|来一场手把手助您打造智能视觉新爆款的技术动手实验
How to build a CMDB driven by consumption scenarios?
以消费场景为驱动的CMDB要怎么建?
想随时、随地、随心使用数据库的朋友们,全体注意!
计算IoU(D2L)
暑假第二周总结博客
SQL函数 TO_DATE(一)