Longest Palindrome Leetcode

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.

 第一思路是用hashmap

public class Solution {
    public int longestPalindrome(String s) {
        HashMap<Character, Integer> h = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (h.containsKey(s.charAt(i))) {
                h.put(s.charAt(i), h.get(s.charAt(i)) + 1);
            } else {
                h.put(s.charAt(i), 1);
            }
        }
        
        int res = 0;
        boolean flag = false;
        for (int num : h.values()) {
            if (num % 2 != 0) {
                flag = true;
            }
            res += num / 2; 
        }
        res = res * 2;
        if (flag) {
            res += 1;
        }
        return res;
        
    }
}

但其实可以不用flag的,有更巧妙的办法。如果回文串不等于字符的长度,那肯定有的char是有奇数个的,所以加1.

public class Solution {
    public int longestPalindrome(String s) {
        HashMap<Character, Integer> h = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (h.containsKey(s.charAt(i))) {
                h.put(s.charAt(i), h.get(s.charAt(i)) + 1);
            } else {
                h.put(s.charAt(i), 1);
            }
        }
        
        int res = 0;
        for (int num : h.values()) {
            res += num / 2; 
        }
        res = res * 2;
        return res == s.length() ? res : res + 1;
        
    }
}

这道题用数组最快,不知道为什么。

用hashset方法也很好,就是不如数组快。

public class Solution {
    public int longestPalindrome(String s) {
        HashSet<Character> hs = new HashSet<>();
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (hs.contains(s.charAt(i))) {
                hs.remove(s.charAt(i));
                count++;
            } else {
                hs.add(s.charAt(i));
            }
        }
        count = count * 2;
        return hs.isEmpty() ? count : count + 1;
        
    }
}

 

posted @ 2017-01-15 09:44  璨璨要好好学习  阅读(134)  评论(0编辑  收藏  举报