본문 바로가기

리트코드/easy

[리트코드] 14. Longest Common Prefix - js

반응형

1. 문제

https://leetcode.com/problems/longest-common-prefix/

 

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

2. 코드

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let common = "";
    let lengthOfStrs = strs.map((el) => el.length)
    let shortestStr = lengthOfStrs.indexOf(Math.min(...lengthOfStrs));

    for(let i=0;i<strs[shortestStr].length;i++){
        let allSame = true;
        for(let j=0;j<strs.length;j++){
            if(strs[j][i] !== strs[shortestStr][i]){
                allSame = false;
                break;
            }
        }
        if(allSame) common += strs[shortestStr][i];
        else break;
    }

    return common;
};
반응형