5

#yyds干货盘点# leetcode算法题:最长回文串

 2 years ago
source link: https://blog.51cto.com/u_13321676/5539130
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# leetcode算法题:最长回文串

原创

灰太狼_cxh 2022-08-03 09:27:44 博主文章分类:leetcode ©著作权

文章标签 回文串 回文字符串 字符串 文章分类 Java 编程语言 阅读数247

给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。

在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。

输入:s = "abccccdd"

我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

输入:s = "a"

输入:s = "bb"

代码实现:

class Solution {
public int longestPalindrome(String s) {
int[] count = new int[128];
int length = s.length();
for (int i = 0; i < length; ++i) {
char c = s.charAt(i);
count[c]++;
}

int ans = 0;
for (int v: count) {
ans += v / 2 * 2;
if (v % 2 == 1 && ans % 2 == 0) {
ans++;
}
}
return ans;
}
}

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK