zoukankan      html  css  js  c++  java
  • LeetCode——409. Longest Palindrome

    题目:

      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.

    大意:

      给出一个由小写或大写字母组成的字符串,找到能被其中的字母组成的最长的回文的长度。

      这是区分大小写的,比如“Aa”就不能认为是回文。

      注意: 
      假设给出的字符串长度不会超过1010。

      例子:

    输入: 
    “abccccdd”
    
    输出: 
    7
    
    解释: 
    最长的回文为“dccaccd”,长度为7。

      回文就是中间有一个单个的字母,两边的字母是对称的。

    • aaadd的最长回文是daaad
    • aaadddcc的最长回文是cdaaadc或者cadddac

      可以总结为:

    • 数目为偶数的字母将全部出现在最长回文中,
    • 奇数就有两种情况,有没有大于1个的,如果有大于1个的。就比如有3个,那么回文长度将加上2。如果有7个就加上6.
    • 如果所有的奇数都不大于1,最后结果再加1即可
    class Solution {
        public int longestPalindrome(String s) {
            int result = 0;
            boolean flag = false;
            int[] a = new int[26*2];
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) < 'a') {
                    a[s.charAt(i) - 'A' + 26]++;
                } else {
                    a[s.charAt(i) - 'a'] ++;
                }
            }
            for(int i:a){
                if(i == 1){
                    flag = true;
                }
                if(i > 1){
                    result += i / 2 * 2;
                    if (i % 2 == 1) flag = true;
                }
            }
            if(flag){
                result++;
            }
            return result;
        }
    }

      这里使用一个26*2的数组记录字幕个数,因为是区分大小写的,每次如果字母数目大于1先除2再乘2,这样偶数不变,奇数将减一。还设置了一个flag变量判断是否存在奇数。

  • 相关阅读:
    Tomcat在Linux下的安装与配置
    Intel S5000VSA(SAS)主板设置RAID 步骤【转】
    eclipse 安装Subversion1.82(SVN)插件
    shell脚本分析nginx日志
    shell脚本抓取网页信息
    shell脚本备份日志
    电力项目十一--js添加浮动框
    电力项目五--主界面分析
    This function has none of DETERMINISTIC, NO SQL
    mysql导入数据失败:mysql max_allowed_packet 设置过小
  • 原文地址:https://www.cnblogs.com/xxbbtt/p/8378043.html
Copyright © 2011-2022 走看看