【LeetCode】 409. Longest Palindrome

来源:互联网 发布:淘宝网鞋子 编辑:程序博客网 时间:2024/04/30 14:49

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.

public class Solution {    public int longestPalindrome(String s) {        Set<Character> hs = new HashSet<Character>();        char[] charArray = s.toCharArray();        int res = 0;        for (int i = 0; i < s.length(); i++) {            char c = charArray[i];            if (hs.contains(c)) {                hs.remove(c);                res++;            } else {                hs.add(c);            }        }        if (hs.isEmpty()) {            return 2 * res;        } else {            return 2 * res + 1;        }    }}


0 0
原创粉丝点击