14-最长公共前缀
标签:字典树 字符串
题目信息
题目地址: 最长公共前缀
题目内容:
javascript
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"]
输出:""
解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] 仅由小写英文字母组成
题解
解法一
思路:
我们先找出数组中的
第一个字符firstStr
,然后得到它的长度len
,创建一个遍历索引index
,一个公共字符串commonStr
,字符串数组剩余字符串数组otherStrs
当
index
小于len
时将
firstStr
的index
位置的字符串和otherStrs
中每一个字符串的索引为index
的字符串比较如果都一样,就将
commonStr
后面添加该字符串,否则直接返回commonStr
代码实现:
javascript
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if(strs.length === 1) return strs[0]
const firstStr = strs[0]
const otherStrs = strs.slice(1)
let index = 0
let commonStr = ''
const len = firstStr.length
while(index < len) {
const curStr = firstStr[index]
// 只要有一个字符串的index索引位置的字符串不等于curStr,就可以直接返回commonStr
if(otherStrs.some(i => i[index] !== curStr)) {
return commonStr
}
commonStr += curStr
index++
}
return commonStr
};