KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (486)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (431)
      • 백준 (187)
      • Programmers (104)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • tree
  • js
  • Level1
  • 정렬
  • 다이나믹 프로그래밍
  • LeetCode
  • 수학
  • C
  • Level 2
  • 문자열
  • Level 0
  • codeup
  • 백준
  • C++
  • Level 1
  • 제코베 JS 100제
  • programmers
  • string
  • recursion
  • 그래프

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Greedy / 2131번 / Longest Palindrome by Concatenating Two Letter Words / JS

2023. 4. 28. 17:22

< 문제 바로가기 >

 

Longest Palindrome by Concatenating Two Letter Words - LeetCode

Can you solve this real interview question? Longest Palindrome by Concatenating Two Letter Words - You are given an array of strings words. Each element of words consists of two lowercase English letters. Create the longest possible palindrome by selecting

leetcode.com

 

< 문제 간단설명 >

words 리스트에서 단어들을 뽑아 조합해서 가장 긴 팰린드롬(좌우대칭)을 만들었을때의 길이를 반환하는 문제이다.

 

/**
 * @param {string[]} words
 * @return {number}
 */
var longestPalindrome = function(words) {
    let symmetryMap = new Map(); // 대칭 단어
    let asymmetryMap = new Map(); // 비대칭 단어

    words.forEach((word) => {
        // 대칭 단어
        if(word[0] === word[1]) {
            symmetryMap.set(word, symmetryMap.get(word) + 1 || 1);
        }
        // 비대칭 단어
        else {
            asymmetryMap.set(word, asymmetryMap.get(word) + 1 || 1);
        }
    });

    let result = 0;
    // 비대칭 단어
    for(const [word, count] of asymmetryMap) {
        // 좌우 반전
        let reflectWord = word[1] + word[0];

        // 맵에 좌우 반전된 단어가 있을 경우
        if(asymmetryMap.has(reflectWord)) {
            let reflectWordCount = asymmetryMap.get(reflectWord);
            // 원래단어와 좌우반전된 단어중 작은 카운트만 더함
            // 남는 단어로는 팰린드롬(대칭)을 만들 수 없기 때문
            result += Math.min(count, reflectWordCount);
        }
    }
    
    // 좌우 대칭을 이루는 단어중에 홀수 카운트가 있는지
    let hasOddCountSymmetryWord = false;
    for(const [_, count] of symmetryMap) {
        if(count % 2 === 1) {
            hasOddCountSymmetryWord = true;
        }
        // 홀수개는 단 한번만 사용가능하고, 나머지는 모두 짝수번 사용해야 대칭을 이룰 수 있음
        result += (count % 2 === 0 ? count : count - 1);
    }
    // 홀수번은 단 한번만 사용가능하므로,
    // 홀수 카운트가 존재한다면 결과값 하나 더해줌
    if(hasOddCountSymmetryWord) {
        result += 1;
    }

    return result * 2;
};

 

저작자표시

'PS > LeetCode' 카테고리의 다른 글

LeetCode / Tree / 226번 / Invert Binary Tree / JS  (0) 2023.04.28
LeetCode / Greedy / 621번 / Task Scheduler / JS  (0) 2023.04.28
LeetCode / Linked List / 148번 / Sort List / JS  (0) 2023.04.28
LeetCode / Linked List / 328번 / Odd Even Linked List / JS  (0) 2023.04.28
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Tree / 226번 / Invert Binary Tree / JS
    • LeetCode / Greedy / 621번 / Task Scheduler / JS
    • LeetCode / Linked List / 148번 / Sort List / JS
    • LeetCode / Linked List / 328번 / Odd Even Linked List / JS
    KimMinJun
    KimMinJun

    티스토리툴바