zoukankan      html  css  js  c++  java
  • leetcode409

    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.

    Input:
    "abccccdd"
    
    Output:
    7
    
    Explanation:
    One longest palindrome that can be built is "dccaccd", whose length is 7.
     
    寻找字符串重组之后能存在的最长的回文串。
    思路清晰:
    用数组记录出现相同字符的个数,只要个数大于2个那么一定能在最后的回文串中出现,如果有单个的只能最多增加以一个长度。
    public class Solution {
        public int longestPalindrome(String s) {
            int[] str = new int[123];
    
            for (int i=0;i<s.length();i++){
                str[s.charAt(i)]++;
            }
    
            int flag = 0;
            int sum = 0;
    
            for (int i=65;i<=90;i++){
                if(str[i] > 1){
                    sum += str[i];
                    if(str[i]%2 != 0){
                        flag = 1;
                        sum--;
                    }
                }else if (str[i] == 1)
                    flag = 1;
            }
            
            for (int i=97;i<=122;i++){
                if(str[i] > 1){
                    sum += str[i];
                    if(str[i]%2 != 0){
                        flag = 1;
                        sum--;
                    }
                }else if (str[i] == 1)
                    flag = 1;
            }
            
            return sum + flag;
        }
    }
    然后根据高手提示,还可以少很多代码,如果最后的回文串长度小于原来的长度,直接加一就可以了,如果和原来相同则不加,因为多余下来的只能有一个字符处于最后回文串的中间位置。
    更改后代码是这样的。
    public class Solution {
        public int longestPalindrome(String s) {
            int[] str = new int[123];
    
            for (int i=0;i<s.length();i++)
                str[s.charAt(i)]++;
    
            int sum = 0;
    
            for (int i=65;i<=122;i++)
                sum += str[i]/2;
            
            sum *= 2;
            
            if(sum < s.length())
                return sum+1;
            else
                return sum;
        }
    }
  • 相关阅读:
    centos6.5 安装redis自动启动
    正则去除字符串中的特殊字符
    数据库存储去重
    pymysql.err.ProgrammingError: (1064)(字符串转译问题)
    [转] Linux下SVN的三种备份方式
    ASP.NET ASHX中访问Session
    ionic 里使用 iframe 可能遇到的问题
    ionic $http 无法正常访问外部web服务器的问题
    Mac下80端口相关
    IIS7 无法写入配置文件web.config 错误
  • 原文地址:https://www.cnblogs.com/linkstar/p/5935232.html
Copyright © 2011-2022 走看看