求字符串中连续不重复最多次数的子串

题目:给定字符串,求该字符串中连续不重复最多次数的子串长度

解决:

function maxStr(s) {
 	let left = 0; // 字符串左指针
 	let right = 1; // 字符串右指针
 	let max = 1; // 最大长度
 	let str; 
 	while (right < s.length) {
 		str = s.slice(left, right);
 		if(str.indexOf(s.charAt(right)) > -1){
 			left ++; // 存在重复字符,左指针前移,切掉原字符串第一个字符
 			continue; // 结束本次循环
 		} else {
 			right ++;
 		}
 		max = Math.max(max,right - left);
 	}
 	return max;  // 6
 }
const a = maxStr("fdsnsdisxfassxjanaDqiabvkacs")
console.log(a)

用到了slice()、indexOf()、charAt()、和Math.max() 方法

slice()

slice()方法也接受两个参数,第一个参数是起始位置,第二个参数是结束位置,但是可以使用负数表示从后往前数的位置。返回一个新字符串,不会影响原始字符串。如果省略第二个参数,该方法会提取字符串的剩余部分。提取的字符串为[start, end)长度的子字符串,其中起始位置包含第一个字符。

let str = "123456789";
console.log(str.slice(0, 5));   //12345
console.log(str.slice(2));      //3456789
console.log(str.slice(3, -2));  //4567
console.log(str);     //123456789

indexOf()

indexOf方法只会返回第一个匹配项的位置。如果数组中存在多个相同的元素,该方法只会返回第一个元素的位置,indexOf()方法是区分大小写的。

const str = "Hello world";
console.log(str.indexOf("o"));      //4
console.log(str.indexOf("e"));      //1
console.log(str.indexOf("E"));      //-1
console.log(str.indexOf("llo"));    //2
console.log(str.indexOf("world"));  //6
console.log(str.indexOf("Hello"));  //0
console.log(str.indexOf("hello"));  //-1

charAt()

charAt()方法用于返回指定位置的字符,如果索引超出字符串范围,则返回空字符串。

const str = "Hello, World!";
console.log(str.charAt(1));   //e
console.log(str.charAt(8));   //o
console.log(str.charAt(20));  //输出空字符串

Math.max()

Math.max() 接受多个数字参数并返回其中的最大数;调用Math.max() ,没有参数,会返回-Infinity

console.log(Math.max(1,2,3,4,5)) //5
console.log(Math.max()) // -Infinity
console.log(Math.max(-Infinity,5))  // 5

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值