409 最长回文串
https://leetcode-cn.com/problems/longest-palindrome/
基本上就是哈希表的思想就好,就看你的代码写的是否够简洁了,这里需要注意的是,所有字母的构造的最长的回文串,那么就是要把所有的字母都要用上的,也就是说当某个字母的字符的个数是奇数个时,也可以组成回文字符串的一部分,只要剔除一个字符就可以了。
- 先定义一个大小52的数字,用来存放小写26个字母和大写26个字母的遍历结果
- 如果有那个字母出现,那么就在对应位置上加一
- 遍历每个字母出现的次数,如果是奇数个,那么就减一加到最终结果中,因为回文中间可以是有一个单独的字母的,所以,中间,如果有奇数个字母的出现的话,那么就最后结果加一就行了。
class Solution {
public int longestPalindrome(String s) {
int[] resArray = new int[52];
char[] chars = s.toCharArray();
int res = 0;
for (int i = 0, len = chars.length; i < len; ++i) {
if (chars[i] >= 'a' && chars[i] <= 'z') {
resArray[chars[i] - 'a'] ++;
} else {
resArray[(chars[i] - 'A') + 26] ++;
}
}
//遍历每个字母出现的次数,如果是奇数个,那么就减一加到最终结果中,因为回文中间可以是有一个单独的字母的,
//所以,中间,如果有奇数个字母的出现的话,那么就最后结果加一就行了。
boolean hasOdd = false;
for (int i = 0; i < 52; ++i) {
if (resArray[i] % 2 == 1 ) {
res += (resArray[i] - 1);
hasOdd = true;
} else if (resArray[i] % 2 == 0) {
res += resArray[i];
}
}
return hasOdd ? res + 1 : res;
}
}
来看看结果,嘻嘻,思想都差不多的。哈哈