409. Longest Palindrome

来源:互联网 发布:淘宝店铺品质退款率 编辑:程序博客网 时间:2024/05/16 16:14

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:7Explanation:One longest palindrome that can be built is "dccaccd", whose length is 7.

解法一:Language-Java Time-O(n) Space-O(n) Run Time-39ms

public class Solution {    public int longestPalindrome(String s) {        Map<Character, Integer> map = new HashMap<Character, Integer>();        boolean bool = false;        int len = 0;        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);            }        }        for(char c : map.keySet())        {            if(map.get(c) % 2 == 0)            {                len += map.get(c);            }            if(map.get(c) >=3 && map.get(c) % 2 != 0)            {                len +=map.get(c) - 1;                bool = true;            }            if(map.get(c) == 1)            {                bool = true;            }        }        if(bool == true)        {            return len + 1;        }else{            return len;        }    }}
0 0
原创粉丝点击