409. Longest Palindrome

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 here.

回文字符串除了中心一个元素,其他的字符必须成对出现。因此可以直接统计字符串里有几组成对的字符。

用数组记录字符出现的次数。
如果数组中某个字符出现了两次,则可以将其归零。然后可以组成的最长回文数字加2。
如果字符串还剩下其他字符未选择,则最长回文数可以加一。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int longestPalindrome(String s) {
int[] alphabet = new int['z' - 'A' + 1];
int count = 0;
int total = s.length();

for(int i = 0; i < s.length(); i++){
int index = s.charAt(i) - 'A';
alphabet[index]+=1;
if( alphabet[index] == 2 ){
total -= 2;
count += 2;
alphabet[index] = 0;
}
}

if(total != 0){
count++;
}

return count;
}
}
Author

Xander

Posted on

2022-04-21

Updated on

2022-05-04

Licensed under

Comments