LeetCode-409. Longest Palindrome (Java)

来源:互联网 发布:淘宝返利网源码 编辑:程序博客网 时间:2024/06/05 14:18

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:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.

------------------------------------------------------------------------------------------------------------------------

题意

求从一个字符串中选取字母构成回文字符串的最大长度

思路

期初的思路就是:若字母出现偶数次,则直接相加,在加上最大的奇数次。

测试失败......才知道奇数位可以减一变成偶数次然后相加。

代码

public class Solution {    public int longestPalindrome(String s) {        int[] lowercase = new int[26];        int[] uppercase = new int[26];        int res = 0;        for (int i = 0; i < s.length(); i++){            char temp = s.charAt(i);            if (temp >= 97) lowercase[temp-'a']++;            else uppercase[temp-'A']++;        }        for (int i = 0; i < 26; i++){            res+=(lowercase[i]/2)*2;            res+=(uppercase[i]/2)*2;        }        return res == s.length() ? res : res+1;    }}


原创粉丝点击