[LeetCode]--409. Longest Palindrome

来源:互联网 发布:java dji开发 编辑:程序博客网 时间:2024/04/30 10:04

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.

public class Solution {    public int longestPalindrome(String s) {        int count = 0;        Map<Character, Integer> map = new HashMap<Character, Integer>();        for (int i = 0; i < s.length(); i++)            if (!map.containsKey(s.charAt(i)))                map.put(s.charAt(i), 1);            else                map.put(s.charAt(i), map.get(s.charAt(i)) + 1);        boolean flag = false;        for (Character c : map.keySet()) {            int temp = map.get(c);            if (temp % 2 == 0)                count += map.get(c);            if (temp % 2 != 0) {                flag = true;                while (temp - 2 > 0) {                    count += 2;                    temp = temp - 2;                }            }        }        if (flag)            count++;        return count;    }}

还有一种解法就是讲出现过的字符都放到hashset中,如果再次碰到则将这个字符remove,len+2,最终的记过就是如果字符出现偶数次则最后在hashset中不存在,如果出现奇数次最后会出现在hashset中,同时每出现两次时已经加到len中,不需要考虑太多其他情况

public int longestPalindrome(String s) {        Set<Character> set = new HashSet<Character>();        int count = 0;        for (char c : s.toCharArray()) {            if (set.contains(c)) {                set.remove(c);                count += 2;            } else {                set.add(c);            }        }        return count + (set.size() > 0 ? 1 : 0);    }
0 0
原创粉丝点击