-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path443. String Compression
More file actions
36 lines (33 loc) · 905 Bytes
/
443. String Compression
File metadata and controls
36 lines (33 loc) · 905 Bytes
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
Problem No.443 String Compression
Question Link- https://leetcode.com/problems/string-compression/description/?envType=study-plan-v2&envId=leetcode-75
Solution in Java:
class Solution {
public int compress(char[] chars) {
StringBuilder sb = new StringBuilder();
int i = 1;
int count = 1;
sb.append(chars[0]);
while(i< chars.length){
if( chars[i] == chars[i-1]){
count++;
}
else{
if (count > 1){
sb.append(count);
}
sb.append(chars[i]);
count = 1;
}
i++;
}
if (count >1){
sb.append(count);
}
for( int j=0; j<sb.length(); j++){
chars[j] = sb.charAt(j);
}
return sb.length();
}
}
Time Complexity: O(n)
Space Complexity: O(1)