Leetcode (Easy): 14. Longest Common Prefix

Eunhye Kim·2024년 3월 22일

알고리즘

목록 보기
9/10

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.

Answer

/**
 * @param {string[]} strs
 * @return {string}
 */
var longestCommonPrefix = function(strs) {
    let prefix = ''
    for(let i = 0; i < strs[0].length; i++){
        let char = strs[0][i]

        for(let j = 1; j < strs.length; j++){
            console.log(strs[1][5])
            if(char !== strs[j][i]) return prefix
        }

        prefix += char
    }
    return prefix
};
profile
개발에 몰두하며 성장하는 도중에 얻은 인사이트에 희열을 느낍니다.

0개의 댓글