-
Notifications
You must be signed in to change notification settings - Fork 14
/
MakeStringCompact.java
51 lines (42 loc) · 1.33 KB
/
MakeStringCompact.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
package by.andd3dfx.string;
/**
* <pre>
* Write a function that transforms string into a new string.
* New string does not contain repeating letters but contains a number after every letter
* that means how many times the letter was repeated in the original string.
* a. “” -> “”
* b. “a” -> “a”
* c. “aaa” -> “a3”
* d. “aaabbcbbb” -> “a3b2cb3”
* </pre>
*
* @see <a href="https://youtu.be/s3sGF7C6cV8">Video solution</a>
*/
public class MakeStringCompact {
public static String transform(String str) {
if (str == null || str.isEmpty()) {
return str;
}
var sb = new StringBuilder();
var chars = str.toCharArray();
var last = chars[0];
var counter = 1;
for (int i = 1; i < chars.length; i++) {
if (chars[i] != last) {
appendWithCounter(sb, last, counter);
last = chars[i];
counter = 1;
} else {
counter++;
}
}
appendWithCounter(sb, last, counter);
return sb.toString();
}
private static void appendWithCounter(StringBuilder sb, char ch, int counter) {
sb.append(ch);
if (counter > 1) {
sb.append(counter);
}
}
}