[LeetCode]14. Longest Common Prefix - JavaScript

롱롱·2022년 8월 12일
0

LeetCode 문제풀이

목록 보기
4/5

LeetCode에서 풀어보기

👀 Problem

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.

✔ Solution

var longestCommonPrefix = function (strs) {
  for (let i = 0; i < strs[0].length; i++) {
    for (let j of strs) {
      if (j[i] != strs[0][i]) {
        return j.slice(0, i);
      }
    }
  }

  return strs[0];
};

strs 배열의 첫번째 단어를 기준으로 배열내 단어들을 비교하면서 다른 문자가 생기면 그 전까지 slice 메서드를 통해 return 하고 만약 모두 같으면 기준이 된 단어를 return하도록 했다.

profile
개발자를 꿈꾸며 공부중입니다.

0개의 댓글