[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长度大小有什么作用么?
- [LC]686. Repeated String Match
- 686. Repeated String Match
- 686. Repeated String Match
- leetcode 686. Repeated String Match
- leetcode 686. Repeated String Match
- leetcode 686. Repeated String Match
- 【LeetCode】686. Repeated String Match
- leetcode 686. Repeated String Match
- Leetcode-686. Repeated String Match(string)
- LWC 52:686. Repeated String Match
- Leetcode | Repeated String Match
- leetcode 686 Repeated String Match
- leetcode题解-686. Repeated String Match && 38. Count and Say
- Repeated String Match问题及解法
- leetcode_686.Repeated String Match ? 待解决
- LeetCode Weekly Contest 52 Repeated String Match(string)
- Leetcode挑战题——Repeated String Match
- LC-Reverse String
- 圆形随手指移动
- 《七点三刻》021期 三新股申购//新浪上线明日头条/12月新规将影响我们生活…
- Android 调用so文件中方法应该注意的 couldn't find "libXXX.so"
- JSON与XML的区别
- Segments POJ
- [LC]686. Repeated String Match
- QT+OpenGL
- 消息“时序”与“一致性”为何这么难
- c#机房合作版---命名规范
- 为什么jsp是servlet?
- C++指针与函数
- maven重命名war插件下的jar名称
- hibernate简答题
- scrapy 解析文档