要求:
给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串,区分大小写,Aa不算一个回文串。
示例:
输入:"abccccdd"
输出:7
dccaccd
思路:
出现回文串只有两种情况:
- 字符出现次数为双数的组合
- 字符出现次数为双数的组合+一个只出现一次的字符
统计字符出现的次数即可,双数才能构成回文。中间允许一个单独数的出现,如"abcba",所以最后如果有字母落单,总长度加一即可。
首先将字符串转变成字符数组,然后遍历该数组,判断对应字符是否在hashset中,如果不在就加进去,如果在就让count++,然后移除该字符。
代码:
class Solution {
public int longestPalindrome(String s) {
if (s.length() == 0)
return 0;
HashSet<Character> hashset = new HashSet<Character>();
char[] chars = s.toCharArray();
int count = 0;
for (int i = 0; i < chars.length; i++) {
if (!hashset.contains(chars[i])) {//hashset中没有该字符
hashset.add(chars[i]);
} else {//hashset中有该字符
hashset.remove(chars[i]);
count++;
}
}
return hashset.isEmpty() ? count*2 : count * 2 + 1;
}
}