LeetCode-Repeated String Match

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82875948

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.

题意:给定一个字符串A和一个字符串B,判断是否可以将A重复多次得到的一个字符串中包含字符串B,返回最小的重复次数;

解法:假设字符串S=A+A+A+A…+A(重复了k次),此时|S|>=|B|,k为满足上面情况的最小值;如果S包含B,那么一定满足A[i:i+len(B)] == B for i = 0, 1, …, len(A) - 1;所以我们只需要考虑是否满足Sk.contains(B)或者Sk+1.contains(B);

Java
class Solution {
    public int repeatedStringMatch(String A, String B) {
        StringBuilder sb = new StringBuilder(A);
        while (sb.length() < B.length()) {
            sb.append(A);
        }
        if (sb.toString().contains(B)) return sb.length() / A.length();
        if (sb.append(A).toString().contains(B)) return sb.length() / A.length();
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82875948