给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。
注意:
假设字符串的长度不会超过 1010。
示例 1:
输入:
"abccccdd"
输出:
7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution409 {
public int longestPalindrome(String s) {
HashMap<String, Integer> hm = new HashMap<String, Integer>();
int outplus = 0;
int out = 0;
for (int i = 0; i < s.length(); i++) {
if (hm.containsKey(s.substring(i, i + 1))) {
hm.put(s.substring(i, i + 1), hm.get(s.substring(i, i + 1)) + 1);
} else {
hm.put(s.substring(i, i + 1), 1);
}
}
for (Map.Entry<String, Integer> entry : hm.entrySet()) {
if (entry.getValue() % 2 == 1) {
outplus = 1;
out = out + entry.getValue() / 2;
} else {
out = out + entry.getValue() / 2;
}
}
return out * 2 + outplus;
}
public static void main(String[] args) {
Solution409 sol = new Solution409();
String s = "abccccdd";
System.out.println(sol.longestPalindrome(s));
}
}
该博客介绍了一种使用HashMap解决Java中寻找给定字符串最长回文子串的方法。通过统计字符出现次数,确定回文串的最大可能长度。示例中,对于输入字符串'abccccdd',算法得出最长回文串长度为7。
282

被折叠的 条评论
为什么被折叠?



