2015-11-30 109 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