LeetCode每日一练【14】
Longest Common Prefix
思路
-
找到原始字符串数组中长度最小的元素作为通用字符串
res
-
遍历字符串数组, 比对元素和
res
的通用字符串- 如果相同, 不做操作
- 如果不相同, 对
res
进行切片处理, 跳出当前循环
-
返回
res
代码
/*
* @Author: fox
* @Date: 2022-04-30 11:16:38
* @LastEditors: fox
* @LastEditTime: 2022-04-30 17:17:30
* @Description: https://leetcode.com/problems/longest-common-prefix/
*/
/**
* @param {string[]} strs 字符串数组
* @return {string} 字符串数组元素通用前缀
*/
const longestCommonPrefix = (strs) => {
console.log(strs)
const mapStrs = strs.map(item => item.length) // 元素长度映射数字组
const minLen = Math.min(...mapStrs); // 映射数组中最短的字符串长度
let res = strs[mapStrs.indexOf(minLen)] // 获取最短的字符串元素
for (let i = 0; i < strs.length; i++) {
for (let j = 0; j < strs[i].length; j++) {
if (!res || !res.length) {
return res
}
if (res[j] !== strs[i][j]) {
res = res.slice(0, j)
break;
}
}
}
return res
};
let strs;
strs = ["flower","flow","flight"]
console.log(longestCommonPrefix(strs)) // 'fl'
strs = ["dog","racecar","car"]
console.log(longestCommonPrefix(strs)) // ''
strs = ["ab", "a"]
console.log(longestCommonPrefix(strs)) // 'a'
strs = ["reflower","flow","flight"]
console.log(longestCommonPrefix(strs)) // ''