码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Repeated String Match

时间:2017-11-09 15:09:08      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:return   span   pre   question   turn   etc   minimum   amp   npos   

 

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直到A的长度大于B。进行一次find即可。

②初始情况下,A的长度大于B的长度。先进行一次find查询,如果找不到可能是因为B在边界连接处,这时重复一次A,再进行一次find查找即可。

class Solution {
public:
    int repeatedStringMatch(string A, string B) {
        int cnt = 1;
        int nA = A.size(), nB = B.size();
        string t = A;
        while (t.size() < nB) {
            t += A;
            cnt++;
        }
        if (t.find(B) != string::npos) {
            return cnt;
        }
        t += A;
        return (t.find(B) != string::npos) ? cnt + 1 : -1;
    }
};
// 19 ms

 

[LeetCode] Repeated String Match

标签:return   span   pre   question   turn   etc   minimum   amp   npos   

原文地址:http://www.cnblogs.com/immjc/p/7808624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!