Javascript
/**
* @param {string} s
* @return {number}
*/
var longestPalindrome = function(s) {
var count=0;
var m=s.split("");
m.sort();
for(var i=0;i<m.length-1;i++)
{
if(m[i]===m[i+1])
{
count+=2;
m.splice(i,2);
i--;
}
}
if(m.length>0) count++;
return count;
};
优解,用了hash
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;
}
}
网友评论