-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path443-压缩字符串.java
132 lines (91 loc) · 3.13 KB
/
443-压缩字符串.java
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(compress(new char[]{'a', 'b', 'c'}));
}
// 方法一
public static int compress(char[] chars) {
if (chars.length == 0 || chars == null){
return 0;
}
if (chars.length == 1){
return 1;
}
ArrayList<Object> list = new ArrayList<>();
char target = chars[0];
int count = 1;
for (int i = 1; i < chars.length; i++) {
if (chars[i] == target){
count++;
}else {
list.add(target);
if (count != 1){
String s = count + "";
char[] charArray = s.toCharArray();
for (char c: charArray) {
list.add(c);
}
}
count = 1;
target = chars[i];
}
}
if ( count != 1 || chars[chars.length-1] != chars[chars.length-2] ){
list.add(target);
if (count != 1){
String s = count + "";
char[] charArray = s.toCharArray();
for (char c: charArray) {
list.add(c);
}
}
}
for (int i = 0; i < list.size(); i++) {
chars[i] = (list.get(i)+"").charAt(0);
}
// System.out.println(list);
System.out.println(Arrays.toString(chars));
return list.size();
}
// 方法二
public static int compressTwo(char[] chars) {
// 边界情况:如果输入数组长度为 1,则无需压缩,直接返回长度 1
if (chars.length == 1) {
return 1;
}
// 初始化指针和计数器
int left = 0;
int count = 1;
// 用于记录压缩后的新数组的索引
int index = 0;
// 开始遍历数组
for (int right = 1; right < chars.length; right++) {
// 如果当前字符与前一个字符相同,则增加计数器
if (chars[right] == chars[right - 1]) {
count++;
} else {
// 如果当前字符与前一个字符不同,则将前一个字符及其计数器添加到新数组中
chars[index++] = chars[left];
// 如果计数器大于 1,则将计数器的数字依次添加到新数组中
if (count > 1) {
for (char digit : String.valueOf(count).toCharArray()) {
chars[index++] = digit;
}
}
// 重置左指针和计数器
left = right;
count = 1;
}
}
// 处理最后一个字符及其计数器
chars[index++] = chars[left];
if (count > 1) {
for (char digit : String.valueOf(count).toCharArray()) {
chars[index++] = digit;
}
}
System.out.println(Arrays.toString(chars));
return index;
}
}