lintCode627:最长回文串

来源:互联网 发布:尼尔森数据分析报告 编辑:程序博客网 时间:2024/06/05 21:03
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        int size = 0 ;        int max = 0;        char[] charArr = s.toCharArray();        int count[] = new int[128];       //将所有字符串中的字符存入字符数组当中     for(int i=0;i<charArr.length;i++){            count[charArr[i]]++;        }       //遍历        for(int i=0;i<128;i++){        //由回文串的特点可知,为偶肯定可以当回文串元素          if(count[i]%2==0){                size += count[i];            }           //判断,如果比记录的max大,则加入前max-1的子串长度,否则直接加入           else if(count[i]%2!=0&&count[i]>max){                if(max!=0)                size  = size + max -1;                max = count[i];            }else{                size +=count[i]-1;            }        }                return size+max;    }}

原创粉丝点击