LeetCode409 Longest Palindrome

2019-02-19 14:27:05 浏览数 (2)

题目

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.

This is case sensitive, for example “Aa” is not considered a palindrome here. 给一个字符串,判断其字符所能组成的回文的最大长度。

解法

依然是统计每个字符的出现次数,在根据不同的次数为结果加上不同的值。

代码语言:javascript复制
public int longestPalindrome(String s) {
        if (s.length() == 0) return 0;
        if (s.length() == 1) return 1;
        int[] recordLow = new int[26];
        int[] recordUp = new int[26];
        int count = 0;
        boolean extra = false;
        for (int i = 0; i < s.length(); i  ) {
            char c = s.charAt(i);
            if (c - 'a' >= 0) recordLow[c - 'a']  ;
            else recordUp[c - 'A']  ;
        }

        for (int i = 0; i < 26; i  ) {

            if (recordLow[i] % 2 == 0)
                count  = recordLow[i] / 2;
            else {
                count  = (recordLow[i] - 1) / 2;
                extra = true;
            }

            if (recordUp[i] % 2 == 0)
                count  = recordUp[i] / 2;
            else {
                count  = (recordUp[i] - 1) / 2;
                extra = true;
            }
        }

        if (extra) return count * 2   1;
        else return count * 2;
    }

0 人点赞