-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompression.java
More file actions
78 lines (62 loc) · 1.81 KB
/
Copy pathCompression.java
File metadata and controls
78 lines (62 loc) · 1.81 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
72
73
74
75
76
77
78
package strings;
public class Compression {
public static String compress(String str) {
/*String newStr = "";
for (int i = 0; i < str.length(); i++) {
Integer count = 1;
while (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
newStr += str.charAt(i);
if (count > 1) {
newStr += count.toString();
}
}
return newStr;
*/
// --- Using StringBuilder ---
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
int count = 1;
while (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
count++;
i++;
}
sb.append(str.charAt(i));
if (count > 1) {
sb.append(count);
}
}
return sb.toString();
}
public static void main(String[] args) {
String str = "aaabbcccdd";
System.out.println(compress(str));
}
}
// String compression (LeetCode 443)
// https://leetcode.com/problems/string-compression/description/
/*
class Solution {
public int compress(char[] chars) {
int index = 0;
int i = 0;
while (i < chars.length) {
char current = chars[i];
int count = 0;
while (i < chars.length && chars[i] == current) {
count++;
i++;
}
chars[index++] = current;
if (count > 1) {
for (char c : Integer.toString(count).toCharArray()) {
chars[index++] = c;
}
}
}
return index;
}
}
*/