zoukankan      html  css  js  c++  java
  • LeetCode 409. Longest Palindrome 最长回文串(C++/Java)

    题目:

    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.

    分析:

    给定一个字符串,用其所有的字符,求能拼成的最大回文串长度。

    统计所有字符出现的频率,计算字符成对的数量,因为只有两个字符才可以组成回文串,当然,如果字符为奇数的话,意味着我们可以将这个字符放在字符串中间来构成回文串。最后数量加和即可。

    程序:

    C++

    class Solution {
    public:
        int longestPalindrome(string s) {
            if(s == "")
                return 0;
            vector<int> a(128, 0);
            for(char &c:s)
                a[c]++;
            int odd = 0;
            int res = 0;
            for(const int num:a){
                res += (num >> 1) << 1;
                if(num & 1)
                    odd = 1;
            }
            return res + odd;
        }
    };

    Java

    class Solution {
        public int longestPalindrome(String s) {
            if(s.length() == 0)
                return 0;
            int[] a = new int[128];
            for(int i = 0; i < s.length(); ++i){
                a[s.charAt(i)]++;
            }
            int res = 0;
            int odd = 0;
            for(final int num:a){
                res += (num >> 1) << 1;
                if((num & 1) == 1)
                    odd = 1;
            }
            return res + odd;
        }
    }
  • 相关阅读:
    11
    10
    09
    08
    201621044079韩烨软件工程作业三
    软工作业二 201621044079韩烨
    软工作业一 201621044079韩烨
    14
    201621044079 week13 网络
    week12 201621044079 流与文件
  • 原文地址:https://www.cnblogs.com/silentteller/p/12301251.html
Copyright © 2011-2022 走看看