当前位置:网站首页>【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 为字符集大小
边栏推荐
猜你喜欢

Golang协程调度器scheduler怎么使用

QPalette palette, frame color fill

计算IoU(D2L)

Leetcode73. Matrix Zeroing

【Day_11 0506】 最近公共祖先

JVM运行时数据区与JMM内存模型是什么

7月30号|来一场手把手助您打造智能视觉新爆款的技术动手实验
Detailed explanation of DBPack SQL Tracing function and data encryption function

C#/VB.NET: extracted from the PDF document all form

QT commonly used global macro definitions
随机推荐
123123123123
EpiSci|片上系统的深度强化学习:神话与现实
C语言理论--笔试面试基础稳固
explain 各字段介绍
sql添加索引
理财产品的月年化收益率怎么算?
SQL function TO_DATE (2)
How to make the fixed-point monitoring equipment display the geographic location on the EasyCVR platform GIS electronic map?
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践
【Day_11 0506】 最近公共祖先
顺序表的简单描述及代码的简单实现
Topology零部件拆解3D可视化解决方案
【Day_08 0426】求最小公倍数
typora操作手册
如何让固定点的监控设备在EasyCVR平台GIS电子地图上显示地理位置?
【Day_12 0507】二进制插入
Friends who want to use the database anytime, anywhere and as you like, all attention!
Leetcode73. Matrix Zeroing
Leetcode71. 简化路径
B005 - STC8 based single chip microcomputer intelligent street light control system