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;
        }
    }
  • 相关阅读:
    ODI Scenario 场景
    数据库权限管理
    Oracle KEEP 分析函数
    Oracle数据仓库套件
    复杂透视表的SQL生成方法
    DW/BI领域的自动化调度方案
    用户画像
    PCP
    理赔系统报表及表模型
    maltab 关于输入输出以及自定义函数的问题
  • 原文地址:https://www.cnblogs.com/silentteller/p/12301251.html
Copyright © 2011-2022 走看看