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

    分析:题目要求找回文串,之前做过一个题目并且总结到,如果回文串一定要从中间往两边考虑,然后还要分长度为奇数和偶数两种情况。在这个题目中,翻译一下:给那么多字符,用这些字符组成一个回文串,最长长度是多少。
    根据回文串的思路,首先出现次数为偶数的字符一定可以用到,为奇数的字符只要次数-1就行了。注意一下最后返回的结果是res还是res+1。代码如下:
     1 class Solution {
     2     public int longestPalindrome(String s) {
     3         Map<Character,Integer> map = new HashMap<>();
     4         for ( char c : s.toCharArray() ) map.put(c,map.getOrDefault(c,0)+1);
     5 //        System.out.println(map);
     6         int res = 0;
     7         boolean havejs = false;
     8         for ( char c : map.keySet() ){
     9             int temp = map.get(c);
    10             if ( temp % 2 ==  0 ) res += temp;
    11             else  {
    12                 if ( temp >= 1 ) havejs = true;
    13                 res += temp-1;
    14             }
    15         }
    16         if ( havejs ) return res+1;
    17         return res;
    18     }
    19 }

          运行时间18ms,看了一下前面的,思路都是用map然后奇偶,不同的就是一些细节处理,就不再优化了。

  • 相关阅读:
    child-selector解释
    a:link a:visited a:hover a:active四种伪类选择器的区别
    Java API —— BigDecimal类
    Java API —— BigInteger类
    Java API —— Random类
    Java API —— Math类
    Java API —— Pattern类
    Shuffle和排序
    剖析MapReduce 作业运行机制
    MapReduce编程系列 — 6:多表关联
  • 原文地址:https://www.cnblogs.com/boris1221/p/9332239.html
Copyright © 2011-2022 走看看