409. Longest Palindrome

My Submissions

Total Accepted: 5510
Total Submissions: 12152
Difficulty: Easy

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.

Hide Company Tags
Google
Hide Tags
Hash Table
Hide Similar Problems
(E) Palindrome Permutation

  public int longestPalindrome(String s) {
        if(s == null || s.length() == 0 ) return 0;

        int count = 0;
        HashSet<Character> set = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            if (set.contains(s.charAt(i))) {
                set.remove(s.charAt(i));
                count++;
            }  else {
                set.add(s.charAt(i));
            }
        }
        
        if (!set.isEmpty()) return count*2  + 1;
        return count * 2;
    }
    // ref: https://discuss.leetcode.com/topic/61300/simple-hashset-solution-java
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容