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").

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

  1. 不知道sb类的.append() .contains()方法,而且转换成字符串时还要.tostring()

[一句话思路]:首先保证达到长度相等的门槛再说,这不难想但也是第一次见

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 加到》B的长度就行了,不用加几千几万次了,因为后面都是重复的:第一次见
  2. 默认返回时是-1时要先写

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

sb类的append方法独出一帜

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int repeatedStringMatch(String A, String B) {
        //cc
        if (B.length() == 0) {
            return -1;
        }
        //ini to the same length
        int count = 0;
        StringBuilder sb = new StringBuilder();
        while (sb.length() < B.length()) {
            sb.append(A);
            count++;
        }
        //enough or not 
        if (sb.toString().contains(B)) {
            return count;
        }
        if (sb.append(A).toString().contains(B)) {
            return ++count;
        }
        //return -1
        return -1;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8639753.html