标题:409最长回文串-简单
题目
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如
"Aa"
不能当做一个回文字符串。注意:
假设字符串的长度不会超过 1010。
示例1
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
代码Java
// 排序 找两两相同点 - 2ms
public int longestPalindrome(String s) {
int result = 0;
char[] chars = s.toCharArray();
Arrays.sort(chars);
for (int i = 1; i < chars.length; i++) {
if (chars[i] == chars[i-1]) {
i++;
result += 2;
}
}
if (result < chars.length)
return result + 1;
else return result;
}
// 哈希存储次数 - 内存使用少 但是还是慢
public int longestPalindrome1(String s) {
int[] big = new int[26];
int[] small = new int[26];
int result = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 'a') {
small[ch - 97] ++;
} else {
big[ch - 65] ++;
}
}
for (int i = 0; i < 26; i++) {
result += big[i] / 2 * 2;
result += small[i] / 2 * 2;
}
if (result < s.length())
return result + 1;
else return result;
}
// 优化数组
public int longestPalindrome2(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 (ans < length)
return ans + 1;
return ans;
}