-
Notifications
You must be signed in to change notification settings - Fork 7
/
demo3.txt
88 lines (80 loc) · 1.55 KB
/
demo3.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package chapter5;
//去掉连续出现k个0的子串
public class demo3 {
public static void main(String[] arfs){
String str = "000100400004000";
// System.out.println(str.indexOf("4000"));
System.out.println(test(str,3));
System.out.println(test1(str,3));
}
public static String test1(String str,int k){
if(k==0){
return str;
}
if(str==null){
return null;
}
StringBuilder sb = new StringBuilder(str);
int count = 0;
for(int i=0;i<sb.length();i++){
if(sb.charAt(i)=='0'){
count++;
}
else{
if(count==k){
for(int j=i-1;count>0;j--,count--){
sb.deleteCharAt(j);
}
}
//无论k和count是否相等,都要清0一下
count = 0;
}
}
//最后还要再判断一次k和count是否相等
if(count==k){
for(int j=sb.length()-1;count>0;j--,count--){
sb.deleteCharAt(j);
}
}
return sb.toString();
}
public static String test(String str,int k){
if(k==0){
return str;
}
if(str==null||str.length()==0){
return null;
}
char[] arr = str.toCharArray();
int count = 0;
int start = -1;
StringBuilder sb = new StringBuilder();
for(int i=0;i!=arr.length;i++){
if(arr[i] == '0'){
count++;
start = start==-1?i:start;
}
else{
if(count==k){
//要开始删除0
while(count--!=0){
arr[start++] = 0;
}
}
start = -1;
count = 0;
}
}
if(count==k){
while(count--!=0){
arr[start++] = 0;
}
}
for(int i=0;i<arr.length;i++){
if(arr[i]!=0){
sb.append(arr[i]);
}
}
return sb.toString();
}
}