[알고리즘] LeetCode - Longest Common Prefix

Jerry·2021년 1월 21일
0

LeetCode

목록 보기
5/73
post-thumbnail

LeetCode - 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.

Solution

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    
    let strLen = strs.length;
    if (strLen == 0) {
        return "";
    }
    let prefix = strs[0];

    if(strLen == 1){
        return prefix;  
    }
    for (let i = 1; i < strLen; i++){
        let str = strs[i];
        let j = 0;
        for (; j < prefix.length; j++){
            if (j > str.length - 1) // 뒤에 단어가 앞의 prefix보다 길이가짧으면
            {
                break;
            }
            if (str[j] != prefix[j]) {
                break;
            }
        }
        if (j == 0) {
            return "";
        }
        prefix=prefix.substring(0, j);
    }
    return prefix;
};

~.~

profile
제리하이웨이

0개의 댓글