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)

블로그 메뉴

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

공지사항

인기 글

태그

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

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / String / 14번 / Longest Common Prefix / JS

2023. 4. 19. 23:27

< 문제 바로가기 >

 

Longest Common Prefix - LeetCode

Can you solve this real interview question? Longest Common Prefix - Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".   Example 1: Input: strs = ["flower","flow"

leetcode.com

 

< 문제 간단설명 >

모든 문자열들에게 공통되는 가장 긴 접두사를 찾아서 반환한다.

 

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    if(strs.length === 1) {
        return strs.at(0);
    }

    strs.sort();
    
    let strFirst = strs.at(0);
    let strLast = strs.at(-1);

    for(let i=0; i<=strFirst.length; i+=1) {
        if(strFirst[i] !== strLast[i]) {
            return strFirst.slice(0, i);
        }
    }

    return strFirst;
};

모든 문자열들이 가지고 있는 공통 접두사를 찾는 문제이다. 반대로 말하면 문자열들중 하나라도 공통되는 것이 없다면 바로 빈 문자열을 반환해주면 된다.

 

일단 문자열 배열을 정렬해준다. 그러면 사전순으로 정렬이 될텐데, 글자가 같은것이 있다면 길이가 짧은게 더 앞으로 올 것이다. 따라서 맨 앞은 사전순으로 앞에 있으면서 길이가 짧은 것, 맨 뒤는 사전순으로 제일 뒤면서 길이가 제일 긴 것이 올 것이다. 그러므로 맨 앞과 맨 뒤만 비교해서 앞에서부터 공통적인것만 뽑아주면 된다.

저작자표시 (새창열림)

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

LeetCode / Linked List / 19번 / Remove Nth Node From End of List / JS  (0) 2023.04.19
LeetCode / String / 43번 / Multiply Strings / JS  (0) 2023.04.19
LeetCode / Simulation / 54번 / Spiral Matrix / JS  (0) 2023.04.18
LeetCode / Implementation / 202번 / Happy Number / JS  (0) 2023.04.18
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Linked List / 19번 / Remove Nth Node From End of List / JS
    • LeetCode / String / 43번 / Multiply Strings / JS
    • LeetCode / Simulation / 54번 / Spiral Matrix / JS
    • LeetCode / Implementation / 202번 / Happy Number / JS
    KimMinJun
    KimMinJun

    티스토리툴바