我不明白为什么我的代码打印的输出为 -1?答案是4



我不明白为什么我的代码打印的输出为 -1?它应该打印 4,因为这是 A 重复 B 成为子字符串的最小次数。

MGiven 两个字符串 A 和 B,找到 A 必须重复的最小次数,使得 B 是它的子字符串。如果没有这样的解决方案,则返回 -1。例如,A = "abcd" 和 B = "cdabcdab"。返回 3,因为通过重复 A 三次("abcdabcdabcd"(,B 是它的子字符串;并且 B 不是重复两次的 A 的子字符串("abcdabcd"(。注意:A 和 B 的长度将在 1 到 10000 之间。

我对字符串 A 的输入是:"abc"我对字符串 B 的输入是:"cabcabca"我的输出是:-1输出应为:4

class Solution {
    public int repeatedStringMatch(String A, String B) {

        String result = A;
        int count = 1;
        if(A.contains(B)) {
        return 1;
        }

        if(A.length() == 1 && B.length() == 1) {
            if(!A.equals(B)) {
                return -1;
            } else {
            return 1;
            }  
        } else {
            while(!result.contains(B)) {
                if(result.length() > B.length()) {
                    result += A;
                    count++;
                    if(A.contains(B)) {
                        return count;
                    } else {
                        return -1;
                    }
                }  
                result += A;
                count++;
            }
        }
        return count;
    }
}

预期 : 4输出: -1

@Macanga很接近,但问题就在这里

} else {
        while(!result.contains(B)) {
            if(result.length() > B.length()) {
                result += A;
                count++;
                if(A.contains(B)) {// here vvv
                    return count;
                } else {
                    return -1;
                }                  //^^^^^^^^
            }  
            result += A;
            count++;
        }
    }
    return count;

很可能它不包含其他字符串,所以繁荣 -1。此外,此if(A.length() == 1 && B.length() == 1) {不做任何有意义的事情基本上 A 不能包含 B,直到它比 B 长,所以你需要继续添加倍数,直到你达到那个长度,然后才检查内容。然后,当倍数长度小于 1000 时继续前进。可能有一些证据表明你只需要达到 B max 长度的 2 倍,但这是一个不同的问题。

而不是做

 if(A.contains(B)) {
       return count;
     } else {
        return -1;
   }

这样做:

if(result.contains(B)) {
           return count;
         } else {
            return -1;
       }

这是一个工作小提琴:https://jsfiddle.net/nhdqL2bs/33/

相关内容

最新更新