[LC]686. Repeated String Match

一、问题描述

Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = "abcd" and B = "cdabcdab". 

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").

Note:
The length of A and B will be between 1 and 10000.


二、我的思路

一个可能包含B串的重复A串最小要达到B串的长度,最大是B串+两个A串的长度。因为最坏的情况就像example给的,两边是A串的片段。如果两边拼上A串一样长的字符串还不能和一个重复A串匹配,则该字符串不能被匹配。

代码:

class Solution {
    public int repeatedStringMatch(String A, String B) {
        if(A== null || B == null || A.length() == 0 || B.length() == 0){
            return -1;
        }
        
        boolean match = false;
        int ret = 1;
        String string = A;
        while(string.length() <= B.length() + 2* A.length()){
            if(string.contains(B)){
                match = true;
                return ret;
            }
            ret ++;
            string += A;
        }
        
        return -1;
    }
}

对比了一下discuss里的思路和代码,真是好烂啊!


三、淫奇技巧

 public int repeatedStringMatch(String A, String B) {

    int count = 0;
    StringBuilder sb = new StringBuilder();
    while (sb.length() < B.length()) {
        sb.append(A);
        count++;
    }
    if(sb.toString().contains(B)) return count;
    if(sb.append(A).toString().contains(B)) return ++count;
    return -1;
}
*不太明白为什么用StringBuilder,和String+的数据结构有什么不同么?

四、知识点

1) KMP可以代替contains函数。时间复杂度O(M+N)。contains函数的实现没有用KMP。原因在这个帖子有写:https://www.zhihu.com/question/27852656

最大的可能是“还没优化到这里”和“常用场景下这个实现已经很快,外加这个实现不需要额外空间开销”。......注意:新的“优化”实现必须要在“常用场景”上能比当前实现有显著性能提升,而且额外空间开销不会很大,才有可能被接受。KMP在“常用场景”上未必能做到这点:初始化的时间开销、额外的空间开销都会成为绊脚石。


五、遗留问题

1. 题目给定A和B长度大小有什么作用么?


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值