我想创建一个算法,它将测试给定的字符串是否为字符串列表的封面字符串。字符串是字符串列表的封面字符串,如果它包含每个字符串中的字符从左到右的顺序。例如,“house”和“hotel”的封面字符串是“ahogjutsel”,非封面字符串的例子是“ahogjsutel”。for循环没有完全迭代
我面临的问题是,我的for循环只是在它返回一个输出之前完成一次迭代。我试图逐个检查列表中的每个字符串,检查每个字符的索引以确保从左到右的顺序保持不变。
任何有关如何修改我的for-loop的建议,以便算法遍历每个字符串中的每个字符将非常有帮助。
公共类StringProcessing {
//Array list to add list of strings for testing.
public static ArrayList<String> stringList = new ArrayList<>();
public static String list1 = "abc";
public static String list2 = "def";
//Algorithm to iterate through each word in stringList and test if it appears in the cover string
//by testing index values.
public static boolean isCover(String coverString){
boolean isCover = false;
stringList.add(list1);
stringList.add(list2);
int size = stringList.size();
int coverSize = coverString.length();
for (int i = 0; i < (size -1) ; i ++){
for (int j = 0; j<stringList.get(i).length(); j++){
if (coverString.indexOf(stringList.get(i).charAt(j)) < coverString.indexOf(stringList.get(i).charAt(j+1))){
return true;
}
else
return isCover;
}
}
return isCover;
}
public static void main(String[] args) {
//For loop only checks if a is before b, then returns true before checking the rest of the characters and strings.
System.out.println(StringProcessing.isCover("abfdec"));
}
}
如果函数的目的是测试的参数是否是一个覆盖字符串,那么你为什么要定义函数内部'stringList'的内容是什么?这会产生副作用,因为'stringList'的值将超出每个函数调用的范围。 – scottb
你能解决这个问题吗? – Perdomoff
@Perdomoff我能够解决这个算法,并使其正常工作,感谢您的所有输入。 – Mickd94