Leetcoude 409 Longest Palindrome

本文介绍了一种用于寻找由给定字符串中的字符构建的最长回文串的方法。该算法考虑了大小写敏感性,并且能处理包含大小写字母的字符串。通过对每个字符出现次数的统计,算法有效地计算出了最长回文串的可能长度。

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:
7

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值