最长回文串

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-palindrome

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

在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串,”A“ 或 ”a“ 最长回文串为1.

点击查看代码
 public static int longestPalindrome(String s) {
        //当前字符串长度为0不会有回文串,直接返回0。
        if (s.length() == 0) {
            return 0;
        }
        //创建一个数组存储每个字符的个数
        int[] nums = new int[128];
        for (int i = 0; i < s.length(); i++) {
            //遍历字符串将每个字符值作为索引存入数组,值为字符的个数
            ++nums[s.charAt(i)];
        }
        //定义最长回文串的长度
        int sum = 0;
        //遍历数组,如果字符个数超过2,则可以作为回文串以中间对称两边的字符。
        for (int num : nums) {
            sum += (num >> 1) * 2;
        }
        //如果遍历完复数字符后值比字符串值小,说明其中有奇数复数字符或者有单字符,则可以作为回文串中间字符。
        if (sum < s.length()) {
            sum++;
        }
        //返回最长回文串
        return sum;
    }

示例 1:

输入:s = "abccccdd"
输出:7
解释:
我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。
示例 2:

输入:s = "a"
输入:1
示例 3:

输入:s = "bb"
输入: 2

posted @ 2022-06-27 22:36  xy7112  阅读(37)  评论(0)    收藏  举报