题目
给定一个字符串str和一个整数k,如果str中正好有连续的k个‘0’字符出现时,把k个连续的‘0’字符去掉,返回处理后的字符串。
举例
str=“A00B”,k=2,返回“AB”
str=“A0000B000”,k=3 返回“A0000B”
public String removeKZeros(String str ,int k ) {
if (str == null || str.length() == 0 || k > str.length()) {
return str;
}
char[] chas = str.toCharArray();
int count = 0;
int strart = -1;
for (int i = 0; i < chas.length; i++) {
if (chas[i] == '0') {
count++;
strart = strart == -1 ? i : strart;
} else {
if (count == k) {
while (count-- != 0) {
chas[strart++] = ' ';
}
} else {
count = 0;
strart = -1;
}
}
}
if (count == k) {
while (count-- != 0) {
chas[strart++] = ' ';
}
}
return String.valueOf(chas).replaceAll("\\s+", "");
}