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;
        }
    }
  • 相关阅读:
    Are You Safer With Firefox?(zz)
    IIS+PHP下调用WebService初试
    垃圾链接和网络欺骗
    微软即将发布64位XP和Win2003 SP1(zz)
    今日个人大事记:)
    GT4 Web Service编译和发布初探
    纪念一下QQ等级和在线时长
    今天安装GT3.9.5碰到的问题
    判断32位整数二进制中1的个数
    Windows 2003 SP1新体验
  • 原文地址:https://www.cnblogs.com/silentteller/p/12301251.html
Copyright © 2011-2022 走看看