Leetcoude 409 Longest Palindrome

来源:互联网 发布:ubuntu 查看命令参数 编辑:程序博客网 时间:2024/06/09 11:30

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.
这个问题犯了几个错误 首先要考虑奇数个字母 并不是只加上最大个 小于max的可以减一算入长度 其次max一定是奇数的 而且max个数的字母可能不止一个
    public int longestPalindrome(String s) {          int[] counter = new int[52];        char[] str = s.toCharArray();        int sum= 0;        int max= 0;        int flag=0;        for(int i =0;i<s.length();i++){            if(str[i]>96){//参照ascii码表            int y = str[i]-80;                counter[y]++;              //  System.out.println(counter[y]);            }            else{                counter[str[i]-65]++;            }                    }                for(int j=0;j<52;j++){        if(counter[j]>max&&counter[j]%2==1 ){        max=counter[j];//找出奇数个的字母的最大值  注意可能不止有一个        }        }      //  System.out.println(max);                for(int j=0;j<52;j++){            if(counter[j]%2==0){                sum +=counter[j];               // System.out.println("sum="+sum);            }                                                              if(counter[j]<max&&counter[j]%2==1 && counter[j]!=0){                        sum+=counter[j]-1;                      //  System.out.println("sum="+sum);                    }                                if(counter[j]==max&&max!=0){                flag++;            }                         }                        if(max!=0){                    sum+=(max-1)*(flag-1)+max;//不止一个max        }               return sum;    }}


0 0
原创粉丝点击