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.
    

    题目标签:Hash Table

      题目给了我们一个string s,让我们找到在这个s 里 最长可能性的回文的长度。

      利用HashMap 先把 s 里的所有char 和它出现次数 做记录,然后遍历map 的keySet,把所有char 长度是偶数的加起来,在把所有char 长度是奇数的 - 1 加起来,最后要判断一下,如果有出现过奇数长度的char,那么在最后答案上再 + 1。

    Java Solution:

    Runtime beats 58.91% 

    完成日期:06/06/2017

    关键词:HashMap

    关键点:对于奇数长度的char,我们也需要把它的 长度 - 1 累加

     1 class Solution 
     2 {
     3     public int longestPalindrome(String s) 
     4     {
     5         HashMap<Character, Integer> map = new HashMap<>();
     6         int len = 0;
     7         boolean oddChar = false;
     8         
     9         for(char c: s.toCharArray())
    10             map.put(c, map.getOrDefault(c, 0) + 1);
    11         
    12         
    13         for(char c: map.keySet())
    14         {
    15             int temp_len = map.get(c);
    16             
    17             if(temp_len % 2 == 0) // even len
    18                 len += temp_len;
    19             else // odd len
    20             {
    21                 if(!oddChar)
    22                     oddChar = true;
    23                 
    24                 len += temp_len - 1;
    25             }
    26         }
    27         
    28         return oddChar ? len + 1 : len;
    29     }
    30 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

  • 相关阅读:
    Python模块之pysnooper
    本站页脚HTML回顶部代码
    本站CSS代码
    Linux使用 tar命令-g参数进行增量+差异备份、还原文件
    mysql定时备份shell脚本
    Linux系统备份与还原
    MYSQL备份与恢复
    技术普及帖:你刚才在淘宝上买了一件东西
    Linux运维工程师前景
    Linux运维工程师需掌握的技能
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7802170.html
Copyright © 2011-2022 走看看