编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
let least = strs[0].length
let leastIndex = 0
let targetByArr = []
strs.forEach((item, index) => {
if (item.length < least) {
least = item.length
leastIndex = index
}
})
let tempArr = strs[leastIndex].split('')
for (let [key, i] of tempArr.entries()) {
let count = 0
strs.forEach(j => {
if (i === j.split('')[key]) {
count++
}
})
if (count === strs.length) {
targetByArr.push(i)
} else {
break
}
}
if (targetByArr.length > 0) {
return targetByArr.join('')
} else {
return '该数组没有公共前缀!'
}
};