zoukankan      html  css  js  c++  java
  • 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.
    his 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.
    

    给定一组字符串,求能够组合出最长的回文串,分为两种情况:

    • 字符串内每个字符都为偶数个,例如:'abccba',出现的字符种类为3,这种毫无疑问最大的长度为2 * 3
    • 某个字符出现了基数次,例如abccccdd,组成的 长度为2*3 + 1
      代码:
    public int longestPalindrome(String s) {
            if(s == null || s.length() == 0) return 0;
            HashSet<Character> hs = new HashSet<Character>();
            int count = 0;
            for(int i = 0; i < s.length(); i++)
            {
                if(hs.contains(s.charAt(i)))
                {
                    hs.remove(s.charAt(i));
                    count ++;
                }
                else
                    hs.add(s.charAt(i));
            }
            if(!hs.isEmpty()) return count * 2 + 1;
            return count * 2;
        }
    
  • 相关阅读:
    java代码split分割数字类
    P1330 封锁阳光大学
    1022 舞会2
    1626 爱在心中
    P2024 食物链(two)
    P1196 银河英雄传说
    P1892 团伙
    P1546 最短网络(最小生成树)
    烦人的幻灯片(拓扑)
    例4.15 奖金(拓扑排序)
  • 原文地址:https://www.cnblogs.com/wxshi/p/7770728.html
Copyright © 2011-2022 走看看