이것저것

409. Longest Palindrome 본문

코딩테스트/leetcode

409. Longest Palindrome

신쥔 2023. 4. 1. 00:16

https://leetcode.com/problems/longest-palindrome/description

 

Longest Palindrome - LeetCode

Can you solve this real interview question? Longest Palindrome - 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,

leetcode.com

문제

문제 해석

소문자 또는 대문자로 구성된 문자열을 지정할 경우 해당 문자로 작성할 수 있는 가장 긴 palindrome의 길이를 반환합니다.
문자는 대소문자를 구분합니다. 예를 들어, "Aa"는 여기서 유사체로 간주되지 않습니다.

 

정답 코드

let countChar = (string, c) => {
    let count;
    let array = Array.from(string);
    
    count = array.reduce((cnt, element) => cnt + (c === element), 0);
    
    return count;
}

let longestPalindrome = (s) => {
    let map = new Map();
    let longestLength = 0;
    let numbersOfOdd = 0;
    let count = 0;
    
    if(s.length === 1)
        return s.length;
    console.log(countChar(s, 'a'));
    for(let char of s)
        map.set(char, countChar(s, char));

    for(let value of map.values())  {
        if(map.size === 1)
            return value;
        if(value % 2 === 0)
            longestLength += value;
        else if (value % 2 === 1)   {
            if(count === 0) {
                longestLength += value;
                count = 1;
            }
            else if(count === 1 || value >= 3)    {
                longestLength += (value - 1);
            }
            else if(count === 1 || value === 1)
                numbersOfOdd = 1;
        }
    }
    return longestLength + numbersOfOdd;
};

 

풀이까지의 사고과정

1. 첫번째 트라이

2. 두번째 트라이

3. 세번째 트라이

4. 네번째 트라이

5. 다섯번째 제출

어쨋든 성공

 

 

참고자료

- palindrome이란

https://ko.wikipedia.org/wiki/%ED%9A%8C%EB%AC%B8

'코딩테스트 > leetcode' 카테고리의 다른 글

589. N-ary Tree Preorder Traversal  (0) 2023.04.02
142. Linked List Cycle II  (0) 2023.03.31