[LintCode] Longest Palindrome
文章目录
Problem
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.
Notice
Assume the length of given string will not exceed 1010.
Example
Given s = "abccccdd" return 7
One longest palindrome that can be built is "dccaccd", whose length is 7.
Solution
public class Solution {
/*
* @param s: a string which consists of lowercase or uppercase letters
* @return: the length of the longest palindromes that can be built
*/
public int longestPalindrome(String s) {
// write your code here
int res = 0;
//Use HashMap to store occurrence, when it's even, res adds 2 and map deletes the key
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (map.containsKey(ch)) {
map.remove(ch);
res += 2;
} else {
map.put(ch, 1);
}
}
if (res < s.length()) res += 1;
return res;
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论