zoukankan      html  css  js  c++  java
  • [LeetCode] 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直到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
  • 相关阅读:
    iframe应用 相互之间发送消息 postMessage
    function angular.bootstrap()
    总结
    1-angular.bind
    jQuery treeTable v 1.4.2
    声明了一个模块和一个控制器AngularJS的处理过程
    angularJs $templateCache
    $.fn.zTree 的使用
    Java异常throws与throw的区别
    Pom报错
  • 原文地址:https://www.cnblogs.com/immjc/p/7808624.html
Copyright © 2011-2022 走看看