코딩테스트/알고리즘 문제풀이

[JAVA] 409. Longest Palindrome

지과쌤 2022. 11. 8.
반응형

목차

    문제

    Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

    Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

     

    Example 1:

    Input: s = "abccccdd"
    Output: 7
    Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
    

    Example 2:

    Input: s = "a"
    Output: 1
    Explanation: The longest palindrome that can be built is "a", whose length is 1.
    

     

    Constraints:

    • 1 <= s.length <= 2000
    • s consists of lowercase and/or uppercase English letters only.

    풀이

    class Solution {
        public int longestPalindrome(String s) {
            int result = 0;
            
            if(s.length() == 0 || s.length() == 1){
                return s.length();
            }
            
            HashSet<Character> hs = new HashSet<Character>();
            
            for (int i = 0; i<s.length(); i++){
                if(hs.contains(s.charAt(i))){
                    hs.remove(s.charAt(i));
                    result++;
                }else{
                    hs.add(s.charAt(i));
                }            
            }
            
            if(hs.size()>0){
                return result*2 + 1;
            }
            
            return result*2;
        }
    }
    반응형

    댓글

    💲 추천 글