【LeetCode】 409. Longest Palindrome 最长回文串(Easy)(JAVA)

【LeetCode】 409. Longest Palindrome 最长回文串(Easy)(JAVA)

题目地址: https://leetcode.com/problems/longest-palindrome/

题目描述:

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.

Note:
Assume the length of given string will not exceed 1,010.

Example:

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.

题目大意

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

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

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

解题方法

字节用一个数组记录下所有的字母次数即可

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

执行用时 : 3 ms, 在所有 Java 提交中击败了 54.44% 的用户
内存消耗 : 37.8 MB, 在所有 Java 提交中击败了 5.25% 的用户

发布了95 篇原创文章 · 获赞 6 · 访问量 2807

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104960268
今日推荐