码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode409

时间:2016-10-07 01:14:31      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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.

Input:
"abccccdd"

Output:
7

Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
 
寻找字符串重组之后能存在的最长的回文串。
思路清晰:
用数组记录出现相同字符的个数,只要个数大于2个那么一定能在最后的回文串中出现,如果有单个的只能最多增加以一个长度。
public class Solution {
    public int longestPalindrome(String s) {
        int[] str = new int[123];

        for (int i=0;i<s.length();i++){
            str[s.charAt(i)]++;
        }

        int flag = 0;
        int sum = 0;

        for (int i=65;i<=90;i++){
            if(str[i] > 1){
                sum += str[i];
                if(str[i]%2 != 0){
                    flag = 1;
                    sum--;
                }
            }else if (str[i] == 1)
                flag = 1;
        }
        
        for (int i=97;i<=122;i++){
            if(str[i] > 1){
                sum += str[i];
                if(str[i]%2 != 0){
                    flag = 1;
                    sum--;
                }
            }else if (str[i] == 1)
                flag = 1;
        }
        
        return sum + flag;
    }
}
然后根据高手提示,还可以少很多代码,如果最后的回文串长度小于原来的长度,直接加一就可以了,如果和原来相同则不加,因为多余下来的只能有一个字符处于最后回文串的中间位置。
更改后代码是这样的。
public class Solution {
    public int longestPalindrome(String s) {
        int[] str = new int[123];

        for (int i=0;i<s.length();i++)
            str[s.charAt(i)]++;

        int sum = 0;

        for (int i=65;i<=122;i++)
            sum += str[i]/2;
        
        sum *= 2;
        
        if(sum < s.length())
            return sum+1;
        else
            return sum;
    }
}

leetcode409

标签:

原文地址:http://www.cnblogs.com/linkstar/p/5935232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!