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.


class Solution {
    public int repeatedStringMatch(String A, String B) {
        int ans = 0;
        int i=0,j=0;
        while(i<B.length()){
            while(j<A.length()&&i<B.length()){
                if(A.charAt(j)==B.charAt(i)){
                    //System.out.println(i+", "+j);
                    i++;
                    j++;
                }else if(ans==0){
                    //stuck here for test cases
                    i=0;
                    j++;
                }else{
                    //System.out.println(i+", "+j);
                    return -1;
                }
            }
            ans++;
            j = 0;
            //i++;
        }
        return ans;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,153评论 0 23
  • 女儿,我想对你说 今天, 看到女儿的朋友圈,有点心伤。错了吗?是...
    萧一一阅读 364评论 0 0
  • 通知: 一对多,比如在开发中,很多控制器都想知道一个事件,所以用通知通知的使用,这篇文章比较好http://www...
    彦子凡阅读 2,103评论 2 4
  • 郭相麟 生活的每一个场景在艺术家眼里,充满着丰富的想象力! 当艺术家拿起手中的画笔,结合现实场景的特点,打开...
    郭相麟阅读 257评论 0 0
  • 这是一个比较敏感的话题,也是一个谈起来就让人长吁短叹,大有壮士断腕之感的问题。每...
    手种青梅阅读 382评论 0 0