686. Repeated String Match 字符串重复后的子字符串查找2
[抄题]:
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]:
[思维问题]:
- 不知道sb类的.append() .contains()方法,而且转换成字符串时还要.tostring()
[一句话思路]:首先保证达到长度相等的门槛再说,这不难想但也是第一次见
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 加到》B的长度就行了,不用加几千几万次了,因为后面都是重复的:第一次见
- 默认返回时是-1时要先写
[二刷]:
- 看错题了尼玛。看成本来重复几次了。不过“窗口法”蛮好的,每次一个窗口
class Solution { public int repeatedStringMatch(String A, String B) { int repeatCount = 0; for (int i = 0; i < B.length(); i++) { //(1,1)是不是就没有了啊 if (B.substring(i, B.length() - 1).contains(A)) { repeatCount++; // } } return repeatCount + 1; } }
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
sb类的append方法独出一帜
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
class Solution { public int repeatedStringMatch(String A, String B) { int repeatCount = 1; String appendedA = A; if (A.contains(B)) return repeatCount; while (true) { appendedA += A; repeatCount ++; if (appendedA.contains(B)) { return repeatCount; } if (appendedA.length() > 100000) { repeatCount = -1; break; } } return repeatCount; } }