/**
* Created by lxw, liwei4939@126.com on 2017/10/31.
* 去掉字符串中连续出现的K个0的子串
*/
public class KZeros {
public static void main(String[] args){
String str1 = "A00B";
int k1 = 2;
String str2 = "A0000B000";
int k2 = 3;
System.out.println(removeKZeros(str1, k1));
System.out.println(removeKZeros(str2, k2));
}
public static String removeKZeros(String str, int k){
if(str == null || k < 1){
return str;
}
char[] charArr = str.toCharArray();
int count =0, start = -1;
for (int i=0 ; i< charArr.length; i++){
if(charArr[i] == '0'){
count++;
start = start == -1 ? i : start;
} else {
if(count == k){
while (count-- != 0){
charArr[start++] = 0;
}
} else {
count = 0;
start = -1;
}
}
}
if(count == k){
while (count-- != 0){
charArr[start++] = 0;
}
}
return String.valueOf(charArr);
}
}
去掉字符串中连续出现的K个0的子串
最新推荐文章于 2022-01-23 14:37:26 发布