-
Notifications
You must be signed in to change notification settings - Fork 1
/
StringCompression.java
48 lines (42 loc) · 1.37 KB
/
StringCompression.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
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/string-compression/
public class StringCompression {
private final char[] input;
public StringCompression(char[] input) {
this.input = input;
}
public int solution() {
char prev = input[0];
int prevCount = 1;
List<Character> charsWithCount = new ArrayList<>();
for (int i = 1; i < input.length; i++) {
char candidate = input[i];
if (prev == candidate) {
prevCount++;
} else {
charsWithCount.add(prev);
if (prevCount > 1) {
String c = String.valueOf(prevCount);
for (int j = 0; j < c.length(); j++) {
charsWithCount.add(c.charAt(j));
}
}
prev = candidate;
prevCount = 1;
}
}
charsWithCount.add(prev);
if (prevCount > 1) {
String c = String.valueOf(prevCount);
for (int j = 0; j < c.length(); j++) {
charsWithCount.add(c.charAt(j));
}
}
for (int i = 0; i < charsWithCount.size(); i++) {
input[i] = charsWithCount.get(i);
}
return charsWithCount.size();
}
}