1

问题陈述是-

在这种情况下包含为空,并且排除有一些值,所以我需要检查 temp 是否存在于排除中,如果 temp 存在于排除中,则不要做任何事情,或者你可以退出循环,但假设 temp不存在排除然后调用一些方法。我在下面实现了相同的功能,不确定我们是否可以进一步改进。在我看来,我们可以在不使用任何布尔值的情况下进行更多改进。因为 main 中的东西需要在一个方法中,并且会被调用很多次

public static void main(String[] args) {

    String temp = "77"; // It can also be 0
    String inclusion = null;
    String exclusion = "100;77;71";
    boolean bb = false;

    if(inclusion !=null) {
        System.out.println("Site Inclusion is not null");
    } else {
        for (String exc: exclusion.split(";")) {
            if(exc.equals(temp)) {
                bb =true;
                break;
            }
        }
        if(!bb) {
            // Call some method
        }
    }
}
4

5 回答 5

1
    exclusion = ";"+exclusion+";";
    temp = ";"+temp+";";

    bb = exclusion.indexOf(temp) >= 0;
    if(!bb) {
        // Call some method
    }

仅当您无法控制传入的排除格式和临时文件时才需要前两行。对问题中的代码进行多次迭代的快速测试需要 1.74 秒,如果使用上述代码进行相同测试则需要 0.38 秒exclude 和 temp 的前导和尾随分号与时序循环的每次迭代连接。如果它们已经有前导分号和尾随分号,则时间会减少到 0.07 秒。作为比较,matches (regex) 需要 1.18 秒,而 StringTokenizer 解决方案需要 0.50 秒。

于 2012-06-05T19:22:46.577 回答
1

我建议使用StringTokenizer而不是String.split(). 正如在这个线程中所讨论的,它要快得多。

public static void main(String[] args) {

    String temp = "77"; // It can also be 0
    String inclusion = null;
    String exclusion = "100;77;71";
    boolean bb = false;

    if(inclusion !=null) {
        System.out.println("Site Inclusion is not null");
    } else {
        StringTokenizer st = new StringTokenizer(exclusion, ";");
        while (st.hasMoreTokens()) {
            if (temp.equals(st.nextToken())) {
                bb = true;
                break;
            }
        }
        if(!bb) {
            // Call some method
        }
    }
}
于 2012-06-05T19:01:41.907 回答
1

我能想到的最有效的实现是

for(int i = exclusion.indexOf(temp);
    i != -1;
    i = exclusion.indexOf(temp, i + 1)) {
  // check if it's bracketed by ; or by the end of the string
  boolean goodStart = i == 0 || exclusion.charAt(i - 1) == ';';
  boolean goodEnd = i + temp.length() == exclusion.length()
    || exclusion.charAt(i + temp.length()) == ';';
  if (goodStart && goodEnd) {
    bb = true;
    break;
  }
}

这避免了正则表达式的开销,使用内置的String.indexOf,并且只使用常量额外变量。

于 2012-06-05T19:03:59.007 回答
0

通过任何方式搜索字符串都是 O(N)。搜索 aHashSet是 O(1)。

用一个HashSet.

于 2012-06-06T01:41:09.660 回答
0
bExists = Arrays.asList(exclusion.split(";")).contains(temp)
于 2012-06-05T19:12:51.007 回答