Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Repeated String Match

$
0
0

题目描述:

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

 


Viewing all articles
Browse latest Browse all 559

Trending Articles