当前位置:网站首页>14. longest common prefix

14. longest common prefix

2022-06-22 23:39:00 Front end plasterer

The longest common prefix

Write a function to find the longest common prefix in the string array .
If no common prefix exists , Returns an empty string “”

Example 1:

     Input : ["flower","flow","flight"]
     Output : "fl"

All input contains only subtitles

solution 1:
Their thinking : Let's take one of them for comparison , Then iterate over the remaining array elements , Compare whether the same position is the same . When it's different , Return previously obtained results , End cycle

    function longestCommonPrefix(strs){
    
        let obj = {
    };
        let str = strs[0]
        if(!str) return "";
        let res = "";
        for (let i = 0; i < str.length; i++) {
    
            let flag = strs.every( item=> {
    
                return item[i] === str[i]
            })
            if(flag){
    
                res += str[i];
            }else{
    
                return res;
            }
        }   
        return res;
    }

solution 2:
Their thinking : Take the first element of the array , Then loop through each character of the first element , Compare characters in the same position as other elements , When the same position of each array element is different , End cycle

    function longestCommonPrefix(strs){
    
        if(!strs.length) return "";
        let idx = 0,n;
        while(idx < strs[0].length){
    
            n = 1;
            while(n < strs.length ){
    
                if(strs[n][idx] != strs[0][idx]){
    
                    return strs[0].substring(0,idx);
                }
                n++;
            }
            idx++;
        }
        return strs[0]
    }
原网站

版权声明
本文为[Front end plasterer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222051389507.html