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

  • 相关阅读:
    物理材质
    铰链joints
    unity 刚体
    扩展方法
    转换操作符方法(非基元类型转换)
    向方法传递可变数量的参数
    参数:可选参数和命名参数
    实例构造器与值类型和引用类型、类型构造器
    成员的可访问性,友元程序集,静态类
    如何删除github上项目的文件
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7802170.html
Copyright © 2011-2022 走看看