409. Longest Palindrome
2026/1/12小于 1 分钟约 269 字
409. Longest Palindrome
难度: Easy
题目描述
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.
Letters are case sensitive, for example, "Aa" is not considered a palindrome.
Example 1:
Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
Example 2:
Input: s = "a" Output: 1 Explanation: The longest palindrome that can be built is "a", whose length is 1.
Constraints:
1 <= s.length <= 2000sconsists of lowercase and/or uppercase English letters only.
解题思路
代码实现
解决方案
java
class Solution {
public int longestPalindrome(String s) {
int[] count = new int[52];
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if ('a' <= c && 'z' >= c) {
count[c-'a']++;
} else {
count[(c-'A') + 26]++;
}
}
int ans = 0;
boolean flag = false;
for (int v : count) {
if (v % 2 == 0) {
ans += v;
} else if (v % 2 == 1) {
flag = true;
ans += v - 1;
}
}
if (flag) {
ans += 1;
}
return ans;
}
}