14. Longest Common Prefix

hand-stencil·2022년 7월 20일
0

LeetCode

목록 보기
1/2

영어공부도 하고 코딩공부도 할 겸 릿코드를 풀어보기로 했다.
난이도 Easy인 것들은 술술 풀면서 넘어갈 줄 알았는데 문제 해결에 대한 컨셉을 잡는게 아직 어렵다!!

오늘 풀어볼 문제

14. 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","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.

문제 풀이

var longestCommonPrefix = function(strs) {
    let curr = strs[0];
    for(let i=1; i<strs.length; i++) {
        let prefix = '';
        let next = strs[i];
        for(let j=0; j<curr.length; j++) {
            if(curr[j] == next[j]) {
                prefix += curr[j];
            } else {
                curr = prefix;
                prefix = '';
                break;
            }
        }    
    }
    if (curr.length == 0) return '';
    else return curr;
};
profile
익숙해지기

0개의 댓글