2015-11-30 107 views
1

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

} 
} 
+0

如果函數的目的是測試的參數是否是一個覆蓋字符串,那麼你爲什麼要定義函數內部'stringList'的內容是什麼?這會產生副作用,因爲'stringList'的值將超出每個函數調用的範圍。 – scottb

+0

你能解決這個問題嗎? – Perdomoff

+0

@Perdomoff我能夠解決這個算法,並使其正常工作,感謝您的所有輸入。 – Mickd94

回答

3
  1. 裏面的if條件,你就返回一個值,這個值結束你的循環。

  2. 編輯將字符串的列表與字符串進行比較。

    編輯11/30/15:字母順序被認爲是決定如果單詞是封面字符串。

更改你的方法:

public class StringProcessing2 { 
public static ArrayList<String> stringList = new ArrayList<>(); 
//Negative Case 
public static String list1 = "house"; 
public static String list2 = "hotel"; 

//Positive Case 
//public static String list1 = "abc"; 
//public static String list2 = "def"; 


public static boolean isCover(String word){ 
    int matchedWords = 0; 
    stringList.add(list1); 
    stringList.add(list2); 

    for(int i = 0; i < stringList.size(); i++){ 
      if(word.contains(String.valueOf(stringList.get(i)))){ 
       matchedWords++;         
     } 
} 
    if(matchedWords == stringList.size()){ 
     return true; 
    } 
    else 
     return false;   
} 


public static void main(String[] args) { 
System.out.println(isCover("ahogjutsel")); 
} 
} 
+1

謝謝澄清,那麼我將如何去修改這個if語句的主體,只在stringList中的每個字符串中的所有字符都爲真時,才返回true。 – Mickd94

+0

@ Mickd94,主要提供的字符串需要讓字符串的數組列表中的每個字符串的所有字符? – Perdomoff

+1

非常感謝您的回答,這非常有幫助。要作爲封面字符串,主要提供的字符串必須包含arraylist中每個字符串的所有字符,並保持字符串從左到右的順序,我試圖在第一段描述中顯示一個例子。 – Mickd94