- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStringCompression.java
More file actions
Latest commit
71 lines (53 loc) · 2.22 KB
/
Copy pathStringCompression.java
File metadata and controls
71 lines (53 loc) · 2.22 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
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
// 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?
// See: https://leetcode.com/problems/string-compression/
packageleetcode.string;
importjava.util.ArrayList;
importjava.util.List;
publicclassStringCompression {
// TODO: solve it using O(1) space (no helper array).
publicintcompress(char[] chars) {
if (chars.length == 1)
return1;
List<int[]> list = newArrayList<>();
intcount = 1;
for (inti = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1])
count++;
if (chars[i] != chars[i + 1] || i == chars.length - 2) {
list.add(newint[] { chars[i], count });
count = 1;
if (chars[i] != chars[i + 1] && i == chars.length - 2)
list.add(newint[] { chars[i + 1], count });
}
}
intpos = 0;
for (int[] pair : list) {
chars[pos] = (char) pair[0];
count = pair[1];
if (count > 1) {
char[] digits = String.valueOf(count).toCharArray();
for (chardigit : digits) {
chars[pos + 1] = digit;
pos += 1;
}
}
pos += 1;
}
// System.out.println(Arrays.toString(chars));
returnpos;
}
publicstaticvoidmain(String[] args) {
StringCompressionsln = newStringCompression();
System.out.println(sln.compress(newchar[] { 'a', 'a', 'b', 'b', 'c', 'c', 'c' }));
System.out.println(sln.compress(newchar[] { 'a' }));
System.out.println(sln.compress(
newchar[] { 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b' }));
System.out.println(sln.compress(newchar[] { 'a', 'a', 'a', 'b', 'b', 'a', 'a' }));
System.out.println(sln.compress(newchar[] { 'a', 'b', 'c' }));
}
}