0%

最长回文串-LeetCode

最长回文串

最长回文串

1
2
3
4
5
6
7
8
9
10
11
12
407.最长回文串:给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。

示例 1:
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。

Implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// @see https://leetcode-cn.com/problems/
public class LongestPalindrome {
public static void main(String[] args) {
String s = "abccccdd";
System.out.println(longestPalindrome(s));
}

public static int longestPalindrome(String s) {
int[] count = new int[128];
//统计每个字符的数量
for (char c: s.toCharArray())
count[c]++;

int ans = 0;
for (int v: count) {
ans += v / 2 * 2;// 字符出现次数>1的字符可构成v/2*2
//当有字符出现奇数次时,可放在回文正中间
if (v % 2 == 1 && ans % 2 == 0)
ans++;
}
return ans;
}
}