[LC]686. Repeated String Match

来源:互联网 发布:插画培训班 知乎 编辑:程序博客网 时间:2024/05/17 06:26

一、问题描述

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长度大小有什么作用么?


原创粉丝点击