409. Longest Palindrome

  • 44.9%

https://leetcode.com/problems/longest-palindrome/

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.

1
2
3
4
5
6
7
8
9
10
11
> Example:
>
> Input:
> "abccccdd"
>
> Output:
> 7
>
> Explanation:
> One longest palindrome that can be built is "dccaccd", whose length is 7.
>

java

23ms, October 18, 2016

https://discuss.leetcode.com/topic/61300/simple-hashset-solution-java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
public int longestPalindrome(String s) {
if(s==null || s.length()==0) return 0;
HashSet<Character> hs = new HashSet<Character>();
int count = 0;
for(int i=0; i<s.length(); i++){
if(hs.contains(s.charAt(i))){
hs.remove(s.charAt(i));
count++;
}else{
hs.add(s.charAt(i));
}
}
if(!hs.isEmpty()) return count*2 + 1;
return count*2;
}
}

cpp

46ms, , October 18, 2016

https://discuss.leetcode.com/topic/61338/what-are-the-odds-python-c

1
2
3
4
5
6
7
8
9
class Solution {
public:
int longestPalindrome(string s) {
int odds = 0;
for(char c='A'; c<='z'; c++)
odds += count(s.begin(), s.end(), c) & 1;
return s.size() - odds + (odds>0);
}
};

python

69ms, October 18, 2016

https://discuss.leetcode.com/topic/61338/what-are-the-odds-python-c

1
2
3
4
5
6
7
8
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
odds = sum(v&1 for v in collections.Counter(s).values())
return len(s) - odds + bool(odds)
谢谢你,可爱的朋友。