409. Longest Palindrome
Posted panini
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
链接:https://leetcode.com/problems/longest-palindrome/#/description
3/22/2017
performance 2%, 40ms。问题到底在哪里?
1 public class Solution { 2 public int longestPalindrome(String s) { 3 HashMap<Character, Integer> frequency = new HashMap<Character, Integer>(); 4 for (int i = 0; i < s.length(); i++) { 5 frequency.put(s.charAt(i), frequency.getOrDefault(s.charAt(i), 0) + 1); 6 } 7 int totalNumber = 0, oddInPalindrome = 0; 8 for (HashMap.Entry<Character, Integer> pair : frequency.entrySet()) { 9 Integer count = pair.getValue(); 10 if (count > 1) { 11 totalNumber += count - count % 2; 12 } 13 if (count % 2 != 0 && oddInPalindrome == 0) oddInPalindrome = 1; 14 } 15 return totalNumber + oddInPalindrome; 16 } 17 }
看了下别人的算法,果然很好
一个39%,23ms的方法,每当有偶数次出现的字符时count++同时从hashset里删除。这个做法有类似的题目,又找不到题目了,看来真是要多次刷才能融会贯通。
1 public int longestPalindrome(String s) { 2 if(s==null || s.length()==0) return 0; 3 HashSet<Character> hs = new HashSet<Character>(); 4 int count = 0; 5 for(int i=0; i<s.length(); i++){ 6 if(hs.contains(s.charAt(i))){ 7 hs.remove(s.charAt(i)); 8 count++; 9 }else{ 10 hs.add(s.charAt(i)); 11 } 12 } 13 if(!hs.isEmpty()) return count*2+1; 14 return count*2; 15 }
还有个老白的Python,又是Collections.counter。这个哥写的Python真的是赏心悦目。他还有很多其他的解法。
1 def longestPalindrome(self, s): 2 odds = sum(v & 1 for v in collections.Counter(s).values()) 3 return len(s) - odds + bool(odds)
另外一个,最后一句没有理解为什么,可能是第二个循环没有仔细理解,但是很喜欢第二个循环里面的做法:/2*2 这种算法情况应该有很多应用。
大小写2个数组目测可以合并成一个。
1 public int longestPalindrome(String s) { 2 int[] lowercase = new int[26]; 3 int[] uppercase = new int[26]; 4 int res = 0; 5 for (int i = 0; i < s.length(); i++){ 6 char temp = s.charAt(i); 7 if (temp >= 97) lowercase[temp-‘a‘]++; 8 else uppercase[temp-‘A‘]++; 9 } 10 for (int i = 0; i < 26; i++){ 11 res+=(lowercase[i]/2)*2; 12 res+=(uppercase[i]/2)*2; 13 } 14 return res == s.length() ? res : res+1; 15 16 }
更多讨论:
https://discuss.leetcode.com/category/536/longest-palindrome
以上是关于409. Longest Palindrome的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 409 Longest Palindrome
[leetcode-409-Longest Palindrome]