409. Longest Palindrome - Easy
前往題目
想法
- 存每個字母的數量,最後疊代取出所有偶數還有一個奇數
思路
想法對了,實作有些情況沒考慮到
- 儲存所有字母的
counts
- 疊代這些
counts
,如果是奇數,注意要把他-1
加到結果裡,因為偶數counts
是需要的 - 遇到偶數就直接把
count
加進去答案 - 最後回傳的時候如果有一個奇數項,就把他加進去
Code
class Solution {
public int longestPalindrome(String s) {
int[] alpha = new int[256];
Arrays.fill(alpha, 0);
// Est. alphabets and their counts
for (int i = 0; i < s.length(); ++i) {
char currChar = s.charAt(i);
alpha[currChar] = alpha[currChar] + 1;
}
int sum = 0;
int flag = 0;
for (int count : alpha) {
// Odd count
if (count % 2 == 1) {
sum += count - 1; // add even count
flag = 1; // Only need one odd
} else { // Even count
sum += count;
}
}
return sum + flag; // Plus the one odd
}
}
409. Longest Palindrome - Easy
https://f88083.github.io/2024/01/27/409-Longest-Palindrome-Easy/