[LeetCode]409. 最长回文串

409. 最长回文串

给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。

在构造过程中,请注意区分大小写。比如 “Aa” 不能当做一个回文字符串。

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

示例 1:

输入: "abccccdd"
输出:  7

解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。




思路

1.使用hashmap,统计重复的字符,重复时,字符串长度+2,同时清除掉重复的值。

   public int longestPalindrome(String s) {
        int count=0;
        HashMap<Character, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (hashMap.containsKey(c)){
                count+=2;
                hashMap.remove(c);
            }else {
                hashMap.put(c,1);
            }
        }
        //最后假如hashmap中还有值,则还可以随便加一个字符串到回文串中
        if (hashMap.size() != 0){
            count++;
        }
        return count;
    }

2.将字符串遍历存入频次数组,统计相同字符串出现个数为奇数值的个数,然后使用字符串的长度-奇数值的个数=偶数值的重复字符串的个数。再加上1就是回文串长度。

    public int longestPalindrome(String s) {
        int[] ints = new int[128];
        
        for (char c : s.toCharArray()) {
            ints[c]++;
        }
        
        int count=0;
        for (int anInt : ints) {
            if (anInt%2==1) { //统计数组中奇数值得个数
                count++;
            }
        }
        return  count==0?s.length():s.length()-count+1;
    }
发布了36 篇原创文章 · 获赞 28 · 访问量 1505

猜你喜欢

转载自blog.csdn.net/tc979907461/article/details/105002007