686. Repeated String Match
class Solution {
public int repeatedStringMatch(String A, String B) {
if(A == null || A.length() == 0 )
{
return -1;
}
if(B == null || B.length()== 0)
{
return 0;
}
int nTimeResult = 1;
StringBuilder sb = new StringBuilder(A);
while(sb.length() < B.length())
{
sb.append(A);
nTimeResult ++;
}
if(sb.toString().contains(B))
{
return nTimeResult;
}
if(sb.append(A).toString().contains(B))
{
return nTimeResult+1;
}
return -1;
}
}
Note:
- 只要sb的長度沒達到B的長度的時候, 就要一直加長度,同時記錄加的次數。
- 一但達到長度,就開始做判斷,這裏有可能達到長度時sb的長度=B的長度,這樣的情況也要繼續再加一次做判斷
- 或者是一開始 B=“aaaaab”, A="ba", 這樣的情況不需要進while判斷,最原始的字符串比較行不通,要再加一次進行判斷纔可以