409. 最长回文串(简单题)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43105156/article/details/102297855

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

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

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

示例 1:

输入:
“abccccdd”

输出:
7

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:

class Solution {
    public int longestPalindrome(String s) {
        char[] ch = s.toCharArray();
        int count = 0;
        int[] an = new int[26];
        int[] bn = new int[26];
        for (int i = 0; i < ch.length; i++) {
            if (ch[i] < 'a') bn[ch[i] - 'A']++;
            else an[ch[i] - 'a']++;
        }
        int res = 0;
        for (int i = 0; i < an.length; i++) {
            if (an[i] >= 2) count += (an[i] % 2 == 0 ? an[i] : an[i] - 1);
            if (an[i] % 2 == 1) res++;
            if (bn[i] >= 2) count += (bn[i] % 2 == 0 ? bn[i] : bn[i] - 1);
            if (bn[i] % 2 == 1) res++;
        }
        return res == 0 ? count : count + 1;
    }
}

简单写法,思路相同,来源题解:

class Solution {
    public int longestPalindrome(String s) {
        int[] count = new int[128];
        for (char c : s.toCharArray()) {
            count[c]++;
        }
        int res = 0;
        for (int i = 0; i < count.length; i++) {
            res += count[i]/2*2;
            if(count[i] % 2 == 1 && res %2 == 0) res++;//只能加一个单个的
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43105156/article/details/102297855