我想創建一個算法,它將測試給定的字符串是否爲字符串列表的封面字符串。字符串是字符串列表的封面字符串,如果它包含每個字符串中的字符從左到右的順序。例如,「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