【发布时间】:2016-03-03 13:25:57
【问题描述】:
我正在尝试创建一个算法来测试给定的字符串是否是字符串列表的覆盖字符串。一个字符串是一个字符串列表的覆盖字符串,如果它包含每个字符串中从左到右顺序的字符。例如,“house”和“hotel”的覆盖字符串为“ahogjutsel”,非覆盖字符串的示例为“ahogjsutel”。
我面临的问题是我的 for 循环在返回输出之前只完成了一次迭代。我试图一个一个地遍历列表中的每个字符串,检查每个字符的索引以确保保持从左到右的顺序。
任何关于如何修改我的 for 循环以便算法遍历每个字符串中的每个字符的建议都会非常有帮助。
公共类 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的值将超出每个函数调用。 -
你能解决这个问题吗?
-
@Perdomoff 我能够解决此算法并使其正常运行,感谢您的所有输入。
标签: java string loops for-loop iteration