Skip to content

Commit d8678cb

Browse files
authored
Create str818.md
1 parent 6f66a0b commit d8678cb

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

2018.11.29-leetcode443/str818.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# 压缩字符串
2+
3+
[英文练习](https://leetcode.com/problems/string-compression/description/) | [中文练习](https://leetcode-cn.com/problems/string-compression/description/)
4+
5+
**题目描述:** 给定一组字符,使用原地算法将其压缩。压缩后的长度必须始终小于或等于原数组长度,数组的每个元素应该是长度为 1 的字符(不是 int 整数类型),在完成原地修改输入数组后,返回数组的新长度。
6+
7+
**示例 1:**
8+
```
9+
输入:
10+
["a","a","b","b","c","c","c"]
11+
12+
输出:
13+
返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"]
14+
15+
说明:
16+
"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。
17+
```
18+
**示例 2:**
19+
```
20+
输入:
21+
["a"]
22+
23+
输出:
24+
返回1,输入数组的前1个字符应该是:["a"]
25+
26+
说明:
27+
没有任何字符串被替代。
28+
```
29+
**示例 3:**
30+
```
31+
输入:
32+
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
33+
34+
输出:
35+
返回4,输入数组的前4个字符应该是:["a","b","1","2"]。
36+
37+
说明:
38+
由于字符"a"不重复,所以不会被压缩。"bbbbbbbbbbbb"被“b12”替代。
39+
注意每个数字在数组中都有它自己的位置。
40+
```
41+
42+
**说明:**
43+
* 所有字符都有一个ASCII值在[35, 126]区间内。
44+
* 1 <= len(chars) <= 1000。
45+
46+
**解题思路:** 用双指针的思想,一个指针从前向后读字符,一个指针从前向后写字符,再通过一个指针记录相同字符序列中的第一个字符下标,用来计算相同字符的数量。
47+
48+
```java
49+
public int compress(char[] chars) {
50+
int anchor = 0, write = 0;
51+
for (int read = 0; read < chars.length; read++) {
52+
if (read + 1 == chars.length || chars[read + 1] != chars[read]) {
53+
chars[write++] = chars[anchor];
54+
if (read > anchor) {
55+
for (char c: ("" + (read - anchor + 1)).toCharArray()) {
56+
chars[write++] = c;
57+
}
58+
}
59+
anchor = read + 1;
60+
}
61+
}
62+
return write;
63+
}
64+
```

0 commit comments

Comments
 (0)