알고리즘

[LeetCode] 14. Longest Common Prefix | 자바스크립트

남양주개발자 2022. 9. 8. 23:09
728x90
반응형

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

🖥 해결방법

function longestCommonPrefix(strs: string[]): string {
    let prefix = "";
    
    for (let i = 0; i < strs[0].length; i++) {
        let isComplete = true;
        const tmpPrefix = strs[0].slice(0, i + 1);
        for (let j = 1; j < strs.length; j++) {
            if (tmpPrefix !== strs[j].slice(0, i + 1)) {
                isComplete = false;
                break;
            }                    
        }
        
        if (isComplete) {
            prefix = tmpPrefix;
        }
    }
    
    return prefix;
};

🌈 결과

// Most Votes Solution
function longestCommonPrefix(strs: string[]): string {
    if (strs === undefined || strs.length === 0) { return ''; }
    
    return strs.reduce((prev, next) => {
        let i = 0;
        while (prev[i] && next[i] && prev[i] === next[i]) i++;
        return prev.slice(0, i);
    });
};
728x90
반응형
그리드형