leetcode 686. Repeated String Match 题解

题目:

给定两个字符串 AB, 寻找重复叠加字符串A的最小次数,使得字符串B成为叠加后的字符串A的子串,如果不存在则返回 -1

举个例子,A = "abcd"B = "cdabcdab"

答案为 3, 因为 A 重复叠加三遍后为 “abcdabcdabcd”,此时 B 是其子串;A 重复叠加两遍后为”abcdabcd”,B 并不是其子串。

注意:

AB 字符串的长度在1和10000区间范围内。

题解:

核心思想是不断重复A得到res,直到长度大于等于B。如果res包含B,则返回true,如果不包含,可以令res再加一次A,此时包含B则返回true,不包含则直接返回false

例如 A = "abcd"B = "cdabcdab"A重复两次后得到res = "abcdabcd",此时res不包含B,但res + A 后则包含B

C++
class Solution {
public:
    int repeatedStringMatch(string A, string B) {
        string res = A;
        int cnt = 1;
        while(res.size() < B.size()){
            res += A;
            cnt++;
        }
        if(res.find(B) != string::npos) {
            return cnt;
        }    
        res += A;
        if(res.find(B) != string::npos) {
            return cnt + 1;
        }    
        return -1;
    }
};
Java
class Solution {
    public int repeatedStringMatch(String A, String B) {
        int lB = B.length();
        String res = A;
        int cnt = 1;
        while( res.length() < lB) {
            res += A;
            cnt++;
        }
        if(res.contains(B)) {
            return cnt;
        }
        res += A;
        if(res.contains(B)) {
            return cnt + 1;
        }
        return -1;
    }
}
Python
class Solution(object):
    def repeatedStringMatch(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: int
        """
        lenB = len(B)
        res = A
        cnt = 1
        while(len(res) < lenB):
            res += A
            cnt += 1
        if(res.find(B) != -1):
            return cnt
        res += A
        if(res.find(B) != -1):
            return cnt + 1
        return -1
JavaScript
/**
 * @param {string} A
 * @param {string} B
 * @return {number}
 */
var repeatedStringMatch = function(A, B) {
    var lenB = B.length;
    var res = A;
    var cnt = 1;
    while (res.length < lenB) {
        res += A;
        cnt++;
    }
    if(res.indexOf(B) != -1) {
        return cnt;
    }
    res += A;
    cnt++;
    if(res.indexOf(B) != -1) {
        return cnt;
    }
    return -1;
};
参考资料

https://leetcode.com/problems/repeated-string-match/discuss/108086/Java-Solution-Just-keep-building-(OJ-Missing-Test-Cases)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值