Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { var str = strs.sort(); //对数组进行排序,对第一个和最后一个进行比较 var last = str[str.length-1]; var first = str[0]; if(!first){ return ""; } var newStr=""; for(var i = 0; i < first.length; i++){ if(first[i] === last[i]){ newStr = newStr + first[i]; }else{ break; } } return newStr; };