leetcode 查找字符串数组共同的前缀longestCommonPrefix
2021-02-08 12:16
标签:function fun ges for循环 查找 code max strong return 我是海大顶瓜瓜 1、从前面查找最长公共前缀 Input: ["flower","flow","flight"] Input: ["dog","racecar","car"] 2、从后面查找最长公共字符串 Input: [‘owner‘, ‘flower‘, ‘fighter‘] Output: "er" 双重for循环真是费头发,以上就是解法,记录一下 leetcode 查找字符串数组共同的前缀longestCommonPrefix 标签:function fun ges for循环 查找 code max strong return 原文地址:https://www.cnblogs.com/linxf/p/12770944.html
Output: "fl"
Example 2:
Output: ""
Explanation: There is no common prefix among the input strings.function getSameFirst(arr) {
let res = ‘‘;
let first;
let max = arr[0].length;
// 第一个循环是遍历字符串的长度
for (let i = 0; i ) {
first = arr[0][i];
// 第二个循环是遍历输入的字符串数组
for (let j = 1,len= arr.length; j ) {
// 把每个字符串拿去一一对比
if (arr[j][i] != first) {
console.log(res);
return res
}
}
res += first
}
}
function getSameEnd(arr) {
let res = ‘‘;
let first = ‘‘;
let max = arr[0].length;
for (let i = 1; i ) {
// 由于是截取最后的字符,所以用slice来截取
first = arr[0].slice(-i);
for (let j = 1,len= arr.length; j ) {
if (arr[j].slice(-i) != first) {
console.log(res);
return res
}
}
res = first
}
}
getSameEnd([‘ofwnqer‘, ‘oflowqer‘, ‘ofightqer‘])
下一篇:python---前端(1)
文章标题:leetcode 查找字符串数组共同的前缀longestCommonPrefix
文章链接:http://soscw.com/index.php/essay/52633.html