coding test/leetCode

[leetCode/JS] 14. Longest Common Prefix

쭘봉 2022. 11. 24. 01:15

문제 설명

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","flight"]
Output: "fl"

 

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

Constraints

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

 


 

내 솔루션

  • 첫 번째 글자를 가져와 긴 것부터 for문 순회 돌림.
  • 타겟문자가 모든 strs 글자의 시작부터 포함되어 있는지 체크.
  • 찾으면 바로 리턴 (가장 긴 문자부터 찾았기 때문에)
var longestCommonPrefix = function(strs) {
  for(let i = strs[0].length - 1; i >= 0; i--) {
    const word = strs[0].substring(0, i+1);
    if(strs.every((str) => str.indexOf(word) === 0)) {
      return word;
    }
  }
  return '';
};

 

감상평

  • 느린 알고리즘 인줄 알았는데, 생각보다 빠른 편이였다. Beats 92%. 뿌듯