LeetCode Repeated String Match 重复叠加字符串匹配

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sun_wangdong/article/details/83099145

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的子串,如果不存在则返回 -1。

举个例子,A = "abcd",B = "cdabcdab"。

答案为 3, 因为 A 重复叠加三遍后为 “abcdabcdabcd”,此时 B 是其子串;A 重复叠加两遍后为"abcdabcd",B 并不是其子串。

注意:

 A 与 B 字符串的长度在1和10000区间范围内。

题解,拿到这道题,就想到要分两种情况,第一种为如果字符串A的长度大于或等于B,这里也要考虑两种情况,即字符串A已经包含有字符串B了,那么直接返回1;如果此时字符串A不包含,但是如果字符串A再添加一遍自己后,也就是现在有两个A了,此时如果包含有B,则返回2;否则返回-1。这是特别需要注意的地方。比如字符串A为“bbbba”,字符串B为"ab",则此时需要考虑第二种情况,需要将字符串A复制两遍,才可以满足包含有字符串B。

第二种情况是字符串A的长度小于B,我采用的方法是在这种情况下再细分为2种子情况,即先算出字符串B最少需要多少个字符串A,即用整除和除余分别得到,如果是被整除了,那也得按照第一种情况下一样,考虑是按照整除添加 or 再加一遍来验证;同样,如果是没有被整除,那也得考虑这两种子情况。

所以待这些情况都考虑完之后,那就能accept了,这种思路是非常简单,但是也非常考验思路的全面性的,所以后期还是需要寻找更简单的思路来解题。

public static int repeatedStringMatch(String A,String B)
    {
        int length1 = A.length();
        int length2 = B.length();
        if(length1 >= length2)
        {
            if(A.contains(B))
                return 1;
            else
            {
                String temp1 = A;
                temp1 += A;
                if(temp1.contains(B))
                    return 2;
                else
                    return -1;
            }
        }
        else
        {
            int num1 = length2 / length1;
            int num2 = length2 % length1;
            String temp2 = A;
            if(num2 != 0)
            {
                for(int i = 1; i <= num1; i++)
                    temp2 += A;
                if(temp2.contains(B))
                    return num1 + 1;
                else
                {
                    temp2 += A;
                    if(temp2.contains(B))
                        return num1 + 2;
                    else
                        return -1;
                }

            }
            else
            {
                for(int i = 1; i <= num1 - 1; i++)
                    temp2 += A;
                if(temp2.contains(B))
                    return num1;
                else
                {
                    temp2 += A;
                    if(temp2.contains(B))
                        return num1 + 1;
                    else
                        return -1;
                }
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/sun_wangdong/article/details/83099145