美文网首页LeetCode
LeetCode 409. 最长回文串

LeetCode 409. 最长回文串

作者: 桐桑入梦 | 来源:发表于2020-03-20 23:10 被阅读0次

    给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。
    在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。

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

    示例 1:
    输入:
    "abccccdd"
    输出:
    7

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

    class Solution {
        public int longestPalindrome(String s) {
            int[] cnt = new int[26 * 2];
            for(int i = 0; i < s.length(); i++){
                if(Character.isLowerCase(s.charAt(i)))
                    cnt[s.charAt(i) - 'a']++;
                if(Character.isUpperCase(s.charAt(i)))
                    cnt[s.charAt(i) - 'A' + 26]++;
            }
            
            boolean hasSingle = false;
            int res = 0;
            
            for(int i = 0; i < cnt.length; i++){
                res += cnt[i] / 2 * 2;
                if(cnt[i] % 2 == 1) 
                    hasSingle = true;
            }
            
            if(hasSingle)
                res++;
            return res;
        }
    }
    
    效果不是很好

    第二次:

    class Solution {
        public int longestPalindrome(String s) {
            int[] cnt = new int[26 * 2];
            int res = 0;
            boolean hasSingle = false;
            
            for(int i = 0; i < s.length(); i++){
                char ch = s.charAt(i);
                if(ch >= 'a' && ch <= 'z')
                    cnt[s.charAt(i) - 'a']++;
                else
                    cnt[s.charAt(i) - 'A' + 26]++;
            }
    
            for(int i = 0; i < cnt.length; i++){
                if(cnt[i] % 2 == 0)
                    res += cnt[i];
                else {
                    res += cnt[i] - 1;
                    hasSingle = true;
                }
            }
            return hasSingle ? res + 1 : res;
        }
    }
    

    相关文章

      网友评论

        本文标题:LeetCode 409. 最长回文串

        本文链接:https://www.haomeiwen.com/subject/gixeyhtx.html