-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path443.java
More file actions
72 lines (63 loc) · 1.58 KB
/
Copy path443.java
File metadata and controls
72 lines (63 loc) · 1.58 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
class Solution {
public int compress(char[] chars) {
StringBuilder s = new StringBuilder();
for (int i=0; i<chars.length; i++) {
int count = 1;
while (i+1 < chars.length && chars[i] == chars[i+1]) {
count++;
i++;
}
s.append(chars[i]);
if (count > 1)
s.append(count);
}
for (int i=0; i<s.length(); i++) {
chars[i] = s.charAt(i);
}
return s.length();
}
}
/*
public int compress(char[] chars) {
int len = chars.length;
int i = 0, k = 0; // i is read pointer, k is write pointer
while (i < len) {
chars[k++] = chars[i];
int j = i + 1;
while (j < len && chars[i] == chars[j])
j++;
if (j-i > 1) {
String current = String.valueOf(j-i);
for (char c : current.toCharArray())
chars[k++] = c;
}
i = j;
}
return k;
}
TC - O(n)
SC - O(1)
*/
/*
int j = 0;
int i = 0;
int len = chars.length;
while(i<len){
char first_ch = chars[i];
int count = 0;
while(i<len && chars[i] == first_ch){
count++;
i++;
}
chars[j] = first_ch;
j++;
if(count>1){
String temp = Integer.toString(count);
for(char c : temp.toCharArray()){
chars[j] = c;
j++;
}
}
}
return j;
*/