2020.12.2每日复习

1668.最大重复子字符串

在这里插入图片描述

class Solution {
    public int maxRepeating(String sequence, String word) {
    	//方法一
        if(sequence.length() < 1 || sequence.length() < word.length()) return 0;
        int res = 0;
        String temp = word;
        while(sequence.contains(temp)) { //如果sequence包含temp
            temp += word; //temp再加一个word,让temp为word的连续字符串,并不断在sequence中判断是否存在temp
            res++;
        }
        return res;

		//方法二
		if(sequence.length() < 1 || sequence.length() < word.length()) return 0;
        int count = 0; //计算当前连续子串的最多个数
        int res = 0; //保留最多的连续子串个数
        int i = -word.length(); //i为上一个word的索引,这里假设初值为 -word.length()
        int k = 0;
        while(true) {
        	//得到word在sequence从 i+word.length() 索引开始第一次出现的索引
            k = sequence.indexOf(word, i + word.length());
            if(k == -1) break;
            //如果两者相等,说明当前是连续子串,上一个word出现后紧接着就是下一个word
            if(k == i + word.length()) {
                count++; //令当前连续子串个数+1
                i = k; //令上一个word的索引更新为这一个,即为 i+word.length()
            } else { //说明连续子串中断
                res = Math.max(res, count); //来判断是否为最长连续子串的个数
                count = 0;
                i = k - word.length(); //令i为当前word出现索引减去一个word的长度,以保证下一次循环时 i+word.length() 能等于当前word出现的索引
            }
        }
        res = Math.max(res, count);
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值