409. Longest Palindrome
2017-07-22 本文已影响12人
DrunkPian0
这题我完全想错了。
求最长回文。统计个个字母出现次数。奇数的保留最大的那个。偶数全保留。这个思路完全错了。
因为奇数中成对的数字也是可以拿来用的。
正确的思路,计算成对出现的pair数。
//求最长回文。~~统计个个字母出现次数。奇数的保留最大的那个。偶数全保留。~~这个思路完全错了。
//因为奇数中成对的数字也是可以拿来用的。
//正确的思路,计算成对出现的pair数。
public int longestPalindrome(String s) {
Set<Character> set = new HashSet<>();
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (!set.contains(s.charAt(i))) {
set.add(s.charAt(i));
} else {
set.remove(s.charAt(i));
count++;
}
}
if (!set.isEmpty()) {
return 2 * count + 1;
} else return 2 * count;
}