当前位置:网站首页>【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 为字符集大小
边栏推荐
猜你喜欢
2022年SQL大厂高频实战面试题(详细解析)
亚马逊云科技Build On2022技能提升计划第二季——揭秘出海爆款新物种背后的黑科技
MySQL数据库————存储过程和函数
Three solutions: npm WARN config global --global, --local are deprecated. Use --location=global instead.
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
QT_QThread线程
XAML WPF项目groupBox控件
计算IoU(D2L)
8月微软技术课程,欢迎参与
C#/VB.NET:从 PDF 文档中提取所有表格
随机推荐
【Error】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat’)
C#/VB.NET: extracted from the PDF document all form
What is the implementation principle of Go iota keyword and enumeration type
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践
C language theory--a solid foundation for the written test and interview
opencv如何实现图像倾斜校正
以消费场景为驱动的CMDB要怎么建?
opencv syntax Mat type summary
加州大学|通过图抽象从不同的第三人称视频中进行逆强化学习
阿里云的域名和ip绑定
Prometheus的Recording rules实践
【Day_08 0426】求最小公倍数
Clip-on multimeter use method, how to measure the voltage, current, resistance?
XAML WPF项目groupBox控件
B002 - Embedded Elderly Positioning Tracking Monitor
成都理工大学&电子科技大学|用于强化学习的域自适应状态表示对齐
QT_QDialog dialog
Zabbix6.0钉钉机器人告警
【Day_12 0507】查找组成一个偶数最接近的两个素数
Basic image processing in opencv