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变量判断是否存在奇数。

  • 相关阅读:
    poj 2418 Hardwood Species
    hdu 3791 二叉搜索树
    九度oj 1544 数字序列区间最小值
    九度oj 1525 子串逆序打印
    九度oj 1530 最长不重复子串
    九度oj 1523 从上往下打印二叉树
    P1190 接水问题
    P1179 数字统计
    P1083 借教室
    P1079 Vigenère 密码
  • 原文地址:https://www.cnblogs.com/xxbbtt/p/8378043.html
Copyright © 2011-2022 走看看