• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

leetcode 686. Repeated String Match 字符串迭代找子串

武飞扬头像
mb64802de6b513d
帮助1

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.

直接使用C 的find函数做查找即可,当A的长度小于B的时候,我们可以先进行重复A,直到A的长度大于等于B,并且累计次数cnt。那么此时我们用find来找,看B是否存在A中,如果存在直接返回cnt。如果不存在,我们再加上一个A,再来找,这样可以处理这种情况A=”abc”, B=”cab”,如果此时还找不到,说明无法匹配,返回-1,

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>

using namespace std;



class Solution 
{
public:
    int repeatedStringMatch(string a, string b)
    {
        int count = 1;
        string aa = a;
        while (aa.length() < b.length())
        {
            count  ;
            aa  = a;
        }

        if (aa.find(b) != aa.npos)
            return count;
        else
        {
            aa  = a;
            if (aa.find(b) != aa.npos)
                return count   1;
            else
                return -1;
        }
    }
};

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibhjai
系列文章
更多 icon
同类精品
更多 icon
继续加载