[LeetCode]Repeated String Match

题目描述:

LeetCode 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.

题目大意:

给定字符串A和B,求A至少重复几次,才能包含B。若不存在,返回-1。

解题思路:

蛮力法

Python代码:

class Solution(object):
    def repeatedStringMatch(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: int
        """
        sa, sb = len(A), len(B)
        x = 1
        while x * sa <= 2 * max(sa, sb):
            if B in A * x: return x
            x += 1
        return -1

 

本文链接:http://bookshadow.com/weblog/2017/10/01/leetcode-repeated-string-match/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论