409. Longest Palindrome

来源:互联网 发布:mac phpmyadmin 配置 编辑:程序博客网 时间:2024/05/17 05:04

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.
给定一个字符串包含大小写,用字符串中的字符组成一个回文串求符合要求的回文串的最大长度,

思路:统计字符串中每个字符出现的次数 再进行处理

刚开始错误:遍历字符串中字符出现的次数,偶数次的直接加进去,奇数次的加最大的。  奇数次的可以去掉一个变成偶数次然后加进去,如 aaaba可以变成abba


因为区分大小写所以建一个数组包含ascII A-z的范围,58个字符,不用担心Z-a之间的6个字符因为它们不会出现统计次数是为0 直接加到len中也不会影响结果

在处理的时候需要考虑奇数的问题,如果是奇数比较它和之前出现的最大奇数次作比较如果大于max则让原来的max-1 加到len中类似aaabb中的a,把这个变成max,否则将这个数-1加到len中,最后返回的时候需要判断 max是否==0 ,如果等于说明字符串中的字符都是出现了偶数次,返回len,如果max!=0 则说明出现了不止一个奇数次,因为在第一次处理max的时候加了一个max-1 是-1 把这个corner去去掉 返回 len+max+1就可以了


run time:11ms

public class Solution {    public int longestPalindrome(String s) {        int []cnt=new int[58];        int max=0;        int len=0;        for(int i=0;i<s.length();i++){            cnt[s.charAt(i)-'A']++;        }        for(int i=0;i<58;i++){            if(cnt[i]%2==0)                len+=cnt[i];            else {                if(cnt[i]>max){                    len+=max-1;                    max=cnt[i];                }                else len=len+cnt[i]-1;            }        }        return max==0?len:len+max+1;    }}


discuss中还有一种解法就是讲出现过的字符都放到hashset中,如果再次碰到则将这个字符remove,len+2,最终的记过就是如果字符出现偶数次则最后在hashset中不存在,如果出现奇数次最后会出现在hashset中,同时每出现两次时已经加到len中,不需要考虑太多其他情况

runtime:18ms


public class Solution {    public int longestPalindrome(String s) {        Set<Character> set = new HashSet<>();        int count = 0;        for (char c : s.toCharArray()) {            if (set.contains(c)) {                set.remove(c);                count += 2;            } else {                set.add(c);            }        }        return count + (set.size() > 0 ? 1 : 0);    }}



0 0