Longest Palindrome (E)
題目
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把偶數部分全部加入,整體只能加一個只出現一次的字符,
代碼實作
Java
class Solution {
public int longestPalindrome(String s) {
int len = 0;
boolean plusOne = false;
int[] hash = new int[52];
for (char c : s.toCharArray()) {
if (c <= 'Z' && c >= 'A') {
hash[c - 'A' + 26]++;
} else {
hash[c - 'a']++;
}
}
for (int i = 0; i < 52; i++) {
if (hash[i] > 1 && hash[i] % 2 == 0) {
len += hash[i];
} else if (hash[i] > 1) {
len += hash[i] - 1;
plusOne = true;
} else if (hash[i] == 1) {
plusOne = true;
}
}
return plusOne ? len + 1 : len;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/3876.html
標籤:其他
下一篇:GMOJ 3569. 正則運算式
