zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    TensorFlow基础篇
    MySql分类
    VISUAL STUDIO 调试
    排序分类
    位分类
    Visio分类
    工作线程AfxBeginThread的使用
    Windows Live Writer配置步骤
    用户界面线程AfxBeginThread的使用
    WIndows 相关知识
  • 原文地址:https://www.cnblogs.com/pk28/p/7624015.html
Copyright © 2011-2022 走看看