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.

    解决方法:

    public class Solution {
        public int longestPalindrome(String s) {
            int size = s.length();
            if (size == 0 || s == null)
                return 0;
            Map<Character,Integer> map = new HashMap<>();
            for (int i = 0; i < size; i++) {
                if (map.containsKey(s.charAt(i))) {
                    map.put(s.charAt(i),map.get(s.charAt(i))+1);
                } else {
                    map.put(s.charAt(i), 1);
                }
            }
            int result=0;
            boolean flag=false;
            for(char c:map.keySet()){
                int f=map.get(c);
                if(f%2==0){
                    result+=f;
                }else{
                    flag=true;
                    result+=f-1;
                }
            }
            return result+(flag?1:0);
        }
    }
  • 相关阅读:
    DAY9 函数初识(各种参数的用法)
    CSS背景
    HTML/CSS 练习
    从JDBC到commons-DBUtils
    SQL
    MYSQL数据库基本操作
    JDBC
    Stream数据流(Collection接口扩充)
    Stack栈
    Map集合接口
  • 原文地址:https://www.cnblogs.com/xiaoduc-org/p/6108373.html
Copyright © 2011-2022 走看看