我正在尝试将数组的连续元素减少为1,但不是所有值都减少:
{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
任何人都可以建议任何改进,因为它认为代码并不完美。
答案 0 :(得分: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();
}
答案 1 :(得分: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();
}
答案 2 :(得分:-1)
int len = 0;
do {
len = str.length();
str = str.replace(replacement + replacement, replacement);
} while (len != str.length());