2018年6月7日 星期四

[LeetCode] 686. Repeated String Match

轉自LeetCode

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>

想法如下
  • 如果 B 要是 A 的 substring,那麼 A 的長度一定要大於等於 B
  • 所以先重複A,直到長度至少等於 B,檢查 B 是不是子字串
  • 如果不是,再重複一次 A(當前一次的長度等於B時,還沒辦法包含所有情況),然後檢查 B 是不是子字串
  • 如果都不是,就回傳 -1
code 如下



Kotlin

沒有留言:

張貼留言