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;
        }
    }
  • 相关阅读:
    提高效率
    kill 挂起 Apache Web Server
    /var/spool/mail/root
    https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py
    top swap
    top load average
    Difference between exit() and sys.exit() in Python
    八进制权限掩码 3位 4位 setuid setgid sticky
    以二进制和八进制方式表示文件模式
    0 lrwxrwxrwx. 1 root root 13 Nov 20 12:44 scala -> scala-2.12.4
  • 原文地址:https://www.cnblogs.com/linkstar/p/5935232.html
Copyright © 2011-2022 走看看