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

B005 - STC8 based single chip microcomputer intelligent street light control system

Leetcode74. Search 2D Matrix
OnePlus 10RT appears on Geekbench, product launch also seems to be approaching

opencv语法Mat类型总结

打开微信客服

B001 - Intelligent ecological fish tank based on STM32
一加OnePlus 10RT出现在Geekbench上 产品发布似乎也已临近

【报错】Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘concat‘)

计算IoU(D2L)

Leetcode73. Matrix Zeroing
随机推荐
Tower Defense Shoreline User Agreement
How to build a CMDB driven by consumption scenarios?
【无标题】setInterval和setTimeout详解
COS 用户实践征文
请你说说多线程
typora操作手册
史上最全的Redis基础+进阶项目实战总结笔记
sql添加索引
【翻译】CNCF培养的OpenMetrics成为一个孵化项目
Basic image processing in opencv
WinRAR | 将多个安装程序生成一个安装程序
想随时、随地、随心使用数据库的朋友们,全体注意!
无需破解,官网安装Visual Studio 2013社区版
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
Leetcode72. 编辑距离
How many steps does it take to convert an ENS domain name into music?
QLineEdit learning and use
B001 - 基于STM32的智能生态鱼缸
加州大学|通过图抽象从不同的第三人称视频中进行逆强化学习
MySQL数据库————流程控制