• leetcode 686. 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的子串
    思路:
    当B的长度小于A的长度时,直接将A扩大两倍与B进行匹配
    当B的长度大于A的长度时,直接将A扩大三倍与B进行匹配,获得匹配的位置i,那么结果就是(i + 1)/A.size()或者(i + 1)/A.size() + 1

    class Solution {
    public:
        int repeatedStringMatch(string A, string B) {
            string k = "";
            if (B.size() <= A.size()) k = A + A;
            else {
                int x = B.size() / A.size() + 2;
                for (int i = 0; i < x; ++i) {
                    k += A;
                }
            }
            int j = 0;
            for (int i = 0; i < k.size(); ++i) {
                if (k[i] == B[j]) {
                    ++j;
                    if (j == B.size()) {
                        if ((i+1) % A.size() == 0) return (i + 1)/A.size();
                        return (i + 1)/A.size() + 1;
                    }
                } else {
                    j = 0;
                }
            }
            return -1;
        }
    };
    
  • 相关阅读:
    Vue(五)模板
    2.typescript-你好世界
    1.typescript-安装
    jquery事件冒泡
    jquery中animate的使用
    Python 环境管理
    CentOS yum 源修改
    Node.js
    端口
    CSV
  • 原文地址:https://www.cnblogs.com/pk28/p/7624015.html
Copyright © 2020-2023  润新知