1. 程式人生 > >LeetCode#686: Repeated String Match

LeetCode#686: Repeated String Match

Description

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.

Solution

對於String A = "abcd"我們考慮這三個例子:String B = "abcdabcdabcd"String B = "abcdabcdab"String B = "cdabcdabcdab"

在第一種情況中,A和B是完全相同的字串,因此只需要重複字串A三次即可得到B;在第二種情況中,B的前兩個abcd是與A一模一樣的,而第三個只有ab沒有cd,此時依然需要重複字串A三次,B才為A的子字串;對於第三種情況則比較特殊,雖然它也包含了三個abcd

,但有一個abcd是被拆分到頭部和尾部的,也就相當於第二種情況的頭部再加上一個cd,此時需要重複字串A四次。

根據以上分析,我們先重複字串A直到它的長度大於或等於字串B,這時候判斷字串B是否為字串A的子字串,如果判斷為否,說明字串B不屬於第一二種情況,則再重複一遍字串判斷其是否為第三種情況,如果是的話則返回遍數,如果不是就說明沒有結果,返回-1。

class Solution {
    public int repeatedStringMatch(String A, String B) {
    	StringBuilder sb = new StringBuilder(A);
    	int
count = 1; 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+1; return -1; } }