0

我正在尝试将数组的连续元素减少到一个,但并非针对所有值,例如:

{3,0,0,0,3,3,3,0,0,0} => {3,0,3,0}

但对于特定的,在我的示例中为 0:

{3,0,0,0,3,3,3,0,0,0} => {3,0,3,3,3,0}

所以只有零(三个是完整的)被减少了。

我有我写的 Java String 工作代码:

public static String removeConsecutive(String str, char remove) {
    char[] chars = str.toCharArray();

    int current = 0;
    int result  = current;
    while (current < chars.length) {
        if (chars[current] == remove) {
            // keep the first occurrence
            chars[result++] = chars[current++];

            // ignore the others
            while (current < chars.length && chars[current] == remove) {
                ++current;
            }
        } else {            
            chars[result++] = chars[current++];
        }
    }

    return new String(chars, 0, result);
}

它可以解决问题:

public static void main(String[] args) {
    System.out.println(removeConsecutive("000300300030303330000", '0'));
}

输出:0303030303330

任何人都可以提出任何改进,因为它认为代码并不完美。

4

3 回答 3

1

认为这更清楚,并且可以完成工作:

public static String removeConsecutive(String str, char remove) {
    StringBuilder sb = new StringBuilder();
    for(char c : str.toCharArray()) {
        int length = sb.length();
        if(c != remove || length == 0 || sb.charAt(length - 1) != c) {
            sb.append(c);
        }
    }
    return sb.toString();
}
于 2013-06-13T02:24:35.103 回答
0

如果它不必就地:

public static String removeConsecutive(String str, char remove) {
   StringBuilder bldr = new StringBuilder();
   int rec = 0;
   for(char curr : str.toCharArray()){
     if(curr == remove){
       if(rec == 0) bldr.append(curr);
       ++rec;
     }
     else{
       rec = 0;
       bldr.append(curr);
     }
   }
   return bldr.toString();
}
于 2013-06-13T02:33:56.617 回答
-1
    int len = 0;
    do {
        len = str.length();
        str = str.replace(replacement + replacement, replacement);
    } while (len != str.length());
于 2013-06-13T02:25:31.120 回答