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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,014評論 0 23
  • 女兒,我想對你說 今天, 看到女兒的朋友圈,有點(diǎn)心傷。錯(cuò)了嗎?是...
    蕭一一閱讀 413評論 0 0
  • 通知: 一對多,比如在開發(fā)中,很多控制器都想知道一個(gè)事件,所以用通知通知的使用,這篇文章比較好http://www...
    彥子凡閱讀 2,127評論 2 4
  • 郭相麟 生活的每一個(gè)場景在藝術(shù)家眼里,充滿著豐富的想象力! 當(dāng)藝術(shù)家拿起手中的畫筆,結(jié)合現(xiàn)實(shí)場景的特點(diǎn),打開...
    郭相麟閱讀 266評論 0 0
  • 這是一個(gè)比較敏感的話題,也是一個(gè)談起來就讓人長吁短嘆,大有壯士斷腕之感的問題。每...
    手種青梅閱讀 416評論 0 0

友情鏈接更多精彩內(nèi)容