본문 바로가기
Web development/Algorithm

[LeetCode] Longest Common Prefix (javascript)

by 자몬다 2021. 2. 26.

공통으로 겹치는 문자열을 찾아내는 문제다.

 

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let result = '';
    if(strs.length <1) return result;
    const first = strs[0]; // flower
    for(let i = 0; i<first.length ; i++){
        const c = first[i]; // f, l, o, w, e, r 
        
        for(let j = 1;j<strs.length;j++){
            if(strs[j][i] !== c) return result; // f"l"ow, fl"o"w
        }
        result += c;
    }
    return result;
};

 

첫 요소를 기준으로 한 글자씩 다음 요소와 글자와 비교해 겹치는 것만 찾아낸다.

 

 

leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/887/

 

Explore - LeetCode

LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.

leetcode.com

 

댓글