lintcode(627)最长回文串

Description:

给出一个包含大小写字母的字符串。求出由这些字母构成的最长的回文串的长度是多少。

数据是大小写敏感的,也就是说,"Aa" 并不会被认为是一个回文串。

 注意事项

假设字符串的长度不会超过 1010

Explanation;

给出 s = "abccccdd" 返回 7

一种可以构建出来的最长回文串方案是 "dccaccd"

Solution:

Record the amount of each character, and check whether it is odd or not.The result equals the sum of each maximum even that less than the amount of each character. If there is at least one odd, the result will add 1.Then returns result.

public class Solution {
    /**
     * @param s a string which consists of lowercase or uppercase letters
     * @return the length of the longest palindromes that can be built
     */
    public int longestPalindrome(String s) {
        // Write your code here
        if(s == null || s.length() == 0){
            return 0;
        }
        boolean hasOod = false;
        int[] record = new int[52];
        for(int i = 0;i<record.length;i++){
            record[i] = 0;
        }
        for(int i = 0;i<s.length();i++){
            char temp = s.charAt(i);
            if(Character.isUpperCase(temp)){
                record[temp - 'A' + 0]++;
            }else{
                record[temp - 'a' + 26]++;
            }
        }
        int result = 0;
        for(int i = 0;i<record.length;i++){
            result += (record[i]/2)*2;
            if(record[i]%2 == 1){
                hasOod = true;
            }
        }
        if(hasOod) result++;
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值