-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringCompression.java
More file actions
46 lines (46 loc) · 1.28 KB
/
StringCompression.java
File metadata and controls
46 lines (46 loc) · 1.28 KB
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
package easy;
/**
* ClassName: StringCompression.java
* Author: chenyiAlone
* Create Time: 2019/8/24 22:33
* Description: No.443 String Compression
*
*Given an array of characters, compress it in-place.
*
* The length after compression must always be smaller than or equal to the original array.
*
* Every element of the array should be a character (not int) of length 1.
*
* After you are done modifying the input array in-place, return the new length of the array.
*
*
* Follow up:
* Could you solve it using only O(1) extra space?
*
*
* Example 1:
*
* Input:
* ["a","a","b","b","c","c","c"]
*
* Output:
* Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
*
*/
public class StringCompression {
public int compress(char[] chars) {
int anchor = 0, write = 0;
for (int read = 0; read < chars.length; read++) {
if (read + 1 == chars.length || chars[read + 1] != chars[read]) {
chars[write++] = chars[anchor];
if (read > anchor) {
for (char c: ("" + (read - anchor + 1)).toCharArray()) {
chars[write++] = c;
}
}
anchor = read + 1;
}
}
return write;
}
}