zoukankan      html  css  js  c++  java
  • 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.

    M1: brute force

    keep string builder and appending until the length A is greater or equal to B
    B要能成为A的字符串,那么A的长度肯定要大于等于B,所以当A的长度小于B的时候,先重复A,直到A的长度大于等于B,并且累计次数cnt。此时找B是否存在A中,如果存在直接返回cnt。如果不存在,加上一个A再找(这样可以处理这种情况A="abc", B="cab")如果此时还找不到,说明无法匹配,返回-1。

    时间:O(M+N),空间:O(max(M, N))

    class Solution {
        public int repeatedStringMatch(String A, String B) {
            StringBuilder sb = new StringBuilder();
            sb.append(A);
            int cnt = 1;
            while(sb.length() < B.length()) {
                sb.append(A);
                cnt++;
            }
            if(sb.toString().contains(B))
                return cnt;
            else if(sb.append(A).toString().contains(B))
                return cnt+1;
            else
                return -1;
        }
    }

    M2: KMP

    时间:O(N)

  • 相关阅读:
    Map 合并
    如何对hashmap按value值排序
    svn使用
    java中key-value数据有重复KEY如何存储
    linux 定时
    java 执行shell命令
    Java相对路径读取文件
    MySql之on duplicate key update详解
    前端学习资源整合
    Number浮点数运算详解
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10049477.html
Copyright © 2011-2022 走看看