JavaScript字符串中两个等号之间的最大子字符串
我们需要编写一个将字符串作为唯一参数的JavaScript函数。
函数应该找到夹在两个相同字符之间的最长字符串,并返回其长度。
例如-
如果输入字符串是-
const str = 'sadtrsewak';
那么输出应该是-
const output = 6;
因为在两个'a'之间,我们拥有长度为6的最长子串。
示例
以下是代码-
const str = 'sadtrsewak';
const longestSubstringBetween = (str = '') => {
const map = {};
let res = -1;
for(let i = 0; i < str.length; i++){
const el = str[i];
if(map.hasOwnProperty(str[i])){
res = Math.max(res, i - map[el] - 1);
}else{
map[el] = i;
};
};
return res;
}
console.log(longestSubstringBetween(str));输出结果以下是控制台输出-
6
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短