lintcode(627)最长回文串

来源:互联网 发布:网络购物商城 编辑:程序博客网 时间:2024/05/17 21:40

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;    }}

 

原创粉丝点击