parsing

Method 1

/ * * *@param {string[]} strs
 * @return {string}* /
var longestCommonPrefix = function(strs) {
    let str = ' '
    let flag = 0
    // If there is only one prefix, there is one prefix
    if(strs.length === 1) {return strs[0]}// Double traversal loop
    for(let i= 0; i < strs[0].length; i++){for(let j = 1; j < strs.length; j++){// The length of the current string is greater than the prefix length, and then the prefix of all strings
            if(strs[j].length >= i && strs[j].startsWith(strs[0].slice(0,i+1))){
                flag ++
            }
        }
        // The prefix is a public prefix as long as the flag = the number of remaining strings
        if(flag === strs.length -1){
            str = strs[0].slice(0,i+1)
        }
        flag = 0
    }
    return str
};
Copy the code

Method 2

var longestCommonPrefix = function(strs) {
    if(strs.length === 0) {return ""
    }
    let ans = strs[0]
    for(let i = 1; i<strs.length; i++){let j = 0
        for(; j < strs[i].length; j++){if(ans[j] ! == strs[i][j]){break
            }
        }
        ans = ans.substr(0,j)
        if(ans === ' ') {return ans
        }
    }
    return ans
};
Copy the code