Leetcode 686.重複疊加字符串匹配

重複疊加字符串匹配

給定兩個字符串 A 和 B, 尋找重複疊加字符串A的最小次數,使得字符串B成爲疊加後的字符串A的子串,若是不存在則返回 -1。 app

舉個例子,A = "abcd",B = "cdabcdab"。 ui

答案爲 3, 由於 A 重複疊加三遍後爲 "abcdabcdabcd",此時 B 是其子串;A 重複疊加兩遍後爲"abcdabcd",B 並非其子串。 spa

注意: 3d

 A 與 B 字符串的長度在1和10000區間範圍內。 code

 

思路

 

 1 class Solution{
 2     public int repeatedStringMatch(String A,String B){
 3         int q=1;
 4         StringBuilder S=new StringBuilder(A);
 5         for(;S.length()<B.length();q++) S.append(A);
 6         if(S.indexOf(B)>=0) return q;
 7         if(S.append(A).indexOf(B)>=0) return q+1;
 8         return -1;
 9     }
10 }

 

 

 

相關文章
相關標籤/搜索