我正在尝试将数组的连续元素减少到一个,但并非针对所有值,例如:
{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
任何人都可以提出任何改进,因为它认为代码并不完美。