您的位置:首页 > 其它

【LeetCode】Longest Palindrome(最长回文串) - Easy

2017-08-26 13:35 423 查看
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.

Notice

Assume the length of given string will not exceed 1010.

给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。

数据是大小写敏感的,也就是说,”Aa” 并不会被认为是一个回文串。

i 注意事项

假设字符串的长度不会超过 1010。

样例

给出 s = “abccccdd” 返回 7

一种可以构建出来的最长回文串方案是 “dccaccd”。

tags

Hash Table, Amazon

分析:

回文串:找到有重复的元素就可以组成回文串 + 中间可以有一个不重复的元素(if there is any)

重复元素:一定成对出现,就算是4个a,也还是两对出现

不重复的先不考虑,将不重复的个数,计作remove。若remove>0,最后返回的个数应+1(because it can be put in the middle)

-涉及contains,考虑将String转为集合判断 + 数组遍历

【Java】
//version 1
public class Solution {
/**
* @param s a string which consists of lowercase or uppercase letters
* @return the length of t
4000
he longest palindromes that can be built
*/
public int longestPalindrome(String s) {
// Write your code here
Set<Character> set = new HashSet();
for(char c : s.toCharArray()){
if(set.contains(c)){//
set.remove(c);//将重复的元素 从set中删去
}else{
set.add(c);//set中只保留不重复的元素
}
}
int remove = set.size();//remove为不重复元素的个数
if(remove > 0){
remove -= 1;//若remove>0,最后返回的个数应+1,也就是删去的个数-1
//(because it can be put in the middle)
}
return s.length() - remove;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: