Open yanggengzhen123 opened 2 years ago
function longestCommonPrefix(strs: string[]): string {
if(strs.length === 0) return '';
let ans = strs[0];
// 遍历strs
for(let i = 1; i < strs.length; i++) {
let j = 0;
for(j; j < ans.length && j < strs[i].length; j++) {
if(ans[j] != strs[i][j]) break;
}
ans = ans.slice(0, j);
if(ans === '') return ans;
}
return ans;
};
function longestCommonPrefix(strs: string[]): string {
let res = strs[0]
for(let str of strs){
for(let i = 0;i < res.length;i++){
if(str[i] !== res[i]){
// 记得 重新赋值res
res = res.slice(0,i)
break
}
}
}
return res
};
function longestCommonPrefix(strs) {
let res = strs[0]
for (let i = 1; i < strs.length; i++) {
let j = 0
while (j < res.length && j < strs[i].length) {
if (res[j] !== strs[i][j])
break
j++
}
res = res.substr(0, j)
}
return res
}
https://leetcode-cn.com/problems/longest-common-prefix/ 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。