2

这是我的第一个问题,它是关于 Java 的。我想实现以下逻辑:

我有两个字符串数组(或字符串列表)。有一个字符串数组 (asu) - M1, M2, M3 ... 以及一个字符串数组 (rzs) - M1, M2, M3 及其所有可能的组合。需要为每个元素(asu)(例如M1)在(rzs)中找到一个元素(M1,M1M2,..),其中包含(例如M1)。示例:从 (asu) 获取 M1 并将开始在 (rzs) 中搜索重复项(包含)。我们在 (rzs) 中找到了 M1M2,它包含 M1。之后,我们应该从数组(列表)中删除这两个元素。我很抱歉我的英语水平^^

String[] asu = { "M1", "M1", "M1", "M3", "M4", "M5", "M1", "M1", "M1", "M4", "M5", "M5" };
String[] rzs = { "M1", "M2", "M3", "M4", "M5", "M1M2", "M1M3", "M1M4", "M1M5", "M2M3", "M2M4", "M2M5", "M3M4", "M3M5", "M4M5", "M1M2M3", "M1M2M4",
        "M1M2M5", "M1M3M4", "M1M3M4", "M1M4M5", "M2M4", "M2M5" };

public static void main(final String[] args) {
    work bebebe = new work();
    bebebe.mywork();
}

public void mywork() {

    System.out.println(Arrays.deepToString(rzs));
    System.out.println(Arrays.deepToString(asu));
    for (int i = 0; i < asu.length; i++) {
        System.out.println("Итерация: " + i);
        for (int j = 0; j < rzs.length; j++) {
            if (asu[i].matches(rzs[j].toString())) {
                System.out.println(i + " элемент (" + asu[i] + ") в ASU равен " + j + " элементу (" + rzs[j] + ") в RZS");
                asu[i] = "";
                rzs[j] = "";
            }
        }
    }
}

结果不会删除子字符串的项目。不满足逻辑。我会很感激你的建议。

4

1 回答 1

2

如果你使用列表,你会得到更好的结果:删除不会要求你取回数组的其余部分,使用列表意味着你的代码逻辑更少

List<string> asu = Arrays.asList("M1","M1","M1","M3","M4","M5","M1","M1","M1","M4","M5","M5");
List<string> rzs = Arrays.asList("M1","M2","M3","M4","M5",
"M1M2","M1M3","M1M4","M1M5","M2M3","M2M4","M2M5","M3M4","M3M5","M4M5"
,"M1M2M3","M1M2M4","M1M2M5","M1M3M4","M1M3M4","M1M4M5","M2M4","M2M5");
public static void main(String[] args) {
work bebebe = new work();
bebebe.mywork();
}

public static void mywork() {
   ArrayList<String> tmp1 = new ArrayList<String>();  
   ArrayList<String> tmp2 = new ArrayList<String>();  
   System.out.println((rzs));
   System.out.println((asu));
   for (String curr : asu){
     for (String currRzs : rzs){
       if (currRzs.contains(curr)) {
          System.out.println(" item("+curr+") in ASU found contained in ("+currRzs+") in RZS");

      if(tmp1.contains(curr) == false)
         tmp1.add(curr);

      if(tmp2.contains(currRzs) == false)
         tmp2.add(currRzs);
       }
      } 
    }

   for (String curr : tmp1){
      asu.remove(curr);
   }

   for (String curr : tmp2){
      rzs.remove(curr);
   }
}
于 2013-08-05T06:54:04.737 回答