Write a function to find the longest common prefix string amongst an array of
If there is no common prefix, return an empty string "".
编写一个函数来查找字符串数组中最长的公共前缀字符串。
如果没有公共前缀,则返回空字符串“”。
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.
思路:通过字符串匹配判断返回的下标是否为零,为零则截取长度加一的字符串继续匹配,直到返回下标不为零为止。
var longestCommonPrefix = function(strs) {
var len = strs.length;
if(strs.length == 0){
console.log(strs.length)
return ""
}else{
console.log(strs.length)
var minLen = strs[0].length;
var count = 0;
for(let i = 1;i < len;i++){
if(strs[i].length < minLen){
minLen = strs[i].length;
}
}
for(let j = 1;j <= minLen;j++){
let leep = true;
for(let i = 0;i < len;i++){
if(strs[i].indexOf(strs[0].slice(0,j)) != 0){
leep = false;
}
}
if(leep == true){
count++;
}else{
return strs[0].slice(0,count);
}
}
return strs[0].slice(0,count);
}
};
网友评论