[LeetCode] Longest Palindrome

아르당·4일 전

LeetCode

목록 보기
86/94
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

소문자 또는 대문자로 구성된 문자열 s가 주어졌을 때, 해당 문자들로 만들 수 있는 가장 긴 회문의 길이를 반환해라.

대소문자를 구분한다. 예를 들어, "Aa"는 회문이 아니다.

Example

#1
Input: s = "abccccdd"
Output: 7
Explanation: 만들 수 있는 가장 긴 회문은 "dccaccd"이며, 길이는 7이다.

#2
Input: s = "a"
Output: 1
Explanation: 만들 수 있는 가장 긴 회문은 길이가 1인 "a"이다.

Constraints

  • 1 <= s.length <= 2000
  • s는 영문 대소문자로 구성된다.

Solved

class Solution {
    public int longestPalindrome(String s) {
        HashSet<Character> charSet = new HashSet<>();
        int length = 0;

        for(char c : s.toCharArray()){
            if(charSet.contains(c)){
                charSet.remove(c);
                length += 2;
            }else{
                charSet.add(c);
            }
        }

        if(!charSet.isEmpty()){
            length += 1;
        }

        return length;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글