409. Longest Palindrome
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example “Aa” is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
解法一
数组记录每个字母对应出现的次数,如果是偶数,加上该字母的次数;如果是奇数,次数-1相加。
public class Solution {
public int longestPalindrome(String s) {
int[] alpha = new int[58];
int ret = 0;
for (int i = 0; i < s.length(); i++) {
alpha[s.charAt(i) - 'A']++;
}
for (int i = 0; i < alpha.length; i++) {
if (alpha[i] > 0) {
if (alpha[i] % 2 == 0) {
ret += alpha[i];
} else if (alpha[i] > 2) {
ret += alpha[i] - 1;
}
}
}
if (ret < s.length()) {
ret++;
}
return ret;
}
}
解法二
解法一的优化版
public class Solution {
public int longestPalindrome(String s) {
int[] alpha = new int[58];
int ret = 0, kind = 0;
for (int i = 0; i < s.length(); i++) {
alpha[s.charAt(i) - 'A']++;
}
for (int i = 0; i < alpha.length; i++) {
ret += (alpha[i] / 2) * 2;
}
return ret == s.length() ? ret : ret + 1;
}
}
解法三
set中添加元素,如果再次出现除掉该元素。
public class Solution {
public int longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return 0;
}
Set<Character> set = new HashSet<Character>();
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (set.contains(s.charAt(i))) {
set.remove(s.charAt(i));
count++;
} else {
set.add(s.charAt(i));
}
}
if (!set.isEmpty()) {
return count * 2 + 1;
}
return count * 2;
}
}