题目
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.
给一个字符串,判断其字符所能组成的回文的最大长度。
解法
依然是统计每个字符的出现次数,在根据不同的次数为结果加上不同的值。
public int longestPalindrome(String s) {
if (s.length() == 0) return 0;
if (s.length() == 1) return 1;
int[] recordLow = new int[26];
int[] recordUp = new int[26];
int count = 0;
boolean extra = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c - 'a' >= 0) recordLow[c - 'a']++;
else recordUp[c - 'A']++;
}
for (int i = 0; i < 26; i++) {
if (recordLow[i] % 2 == 0)
count += recordLow[i] / 2;
else {
count += (recordLow[i] - 1) / 2;
extra = true;
}
if (recordUp[i] % 2 == 0)
count += recordUp[i] / 2;
else {
count += (recordUp[i] - 1) / 2;
extra = true;
}
}
if (extra) return count * 2 + 1;
else return count * 2;
}
本文介绍了一种求解给定字符串中能组成最长回文串的方法。通过统计字符串中每个字符的出现次数,该算法能够高效地计算出最大回文长度。特别注意的是,这里的回文判定对大小写敏感。
383

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



