gpt4 book ai didi

java - 在长 `String`中查找单词的排列

转载 作者:太空宇宙 更新时间:2023-11-04 13:37:36 25 4
gpt4 key购买 nike

我试图在第二个字符串中找到单词(本例中为“abc”)的所有排列。但我收到了StringOutOFBoundException。代码有什么问题?

public class StringPermutations {

public static void main(String[] args){

int count = findPermutations("abc", "Helloabcwwwabcwwqqqqqqaawwbcwwwwabcabc");
System.out.println("The number of the permutations of abc is " + count);
}

public static int findPermutations(String word, String longString){
int count = 0;
int length = word.length();

String myString = "";
for(int i = 0; i < longString.length() - length; i++){
if(longString.substring(i, longString.length() - length - i).equals(word)){
count++;
}
}
return count;
}
}

最佳答案

在循环中,子字符串的第二个参数有时为负数。您希望它是 longString.substring(i, i + length)

关于java - 在长 `String`中查找单词的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31552319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com