题目:
现在我们考虑一下可以构成回文串的两种情况:
- 字符出现次数为双数的组合
- 字符出现次数为双数的组合+一个只出现一次的字符
思路:
统计字符出现的次数即可,双数才能构成回文。因为允许中间一个数单独出现,比如"abcba”,所以如果最后有字母落单,总长度可以加1。首先将字符串转变为字符数组。然后遍历该数组,判断对应字符是否在hashset中,如果不在就加进去,如果在就让count++,然后移除该字符!这样就能找到出现次数为双数的字符个数。
实现时注意临界特殊情况的考虑:
比如在本题设计方法时,记得判断传入的字符串是否为空
实现如下:
package cn.palindrome;
import java.util.HashSet;
/**
* @program: algorithm_learn
* @description: 构造最长回文串
* @author: Mr.Luo
* @create: 2020-06-09 22:47
*/
public class Solution_1 {
public static int longPalindrome(String s){
if (s.length() == 0 || s == null){
return 0;
}
//用于存放字符
HashSet<Character> hashset = new HashSet<>();
char[] chars = s.toCharArray();
int count = 0;
for (int i = 0; i < chars.length; i++) {
if (!hashset.contains(chars[i])){
hashset.add(chars[i]);
}else {
hashset.remove(chars[i]);
count++;
}
}
return hashset.isEmpty() ? count * 2 : count * 2 + 1;
}
public static void main(String[] args) {
String s = "abcccccdd";
System.out.println(longPalindrome(s));
}
}