forked from avinashbest/java-coding-ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressString.java
More file actions
63 lines (56 loc) · 1.84 KB
/
Copy pathCompressString.java
File metadata and controls
63 lines (56 loc) · 1.84 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
package strings.Assignment;
import java.util.Scanner;
/*Write a program to do basic string compression. For a character which is consecutively repeated more than once, replace consecutive duplicate occurrences with the count of repetitions.
Example:
If a string has 'x' repeated 5 times, replace this "xxxxx" with "x5".
The string is compressed only when the repeated character count is more than 1.
Note :
Consecutive count of every character in the input string is less than or equal to 9.
Input Format:
The first and only line of input contains a string without any leading and trailing spaces.
Output Format:
The only line of output prints the updated string.
Note:
You are not required to print anything. It has already been taken care of.
Constraints:
0 <= N <= 10^6
Where N is the length of the input string.
Time Limit: 1 second
Sample Input 1:
aaabbccdsa
Sample Output 1:
a3b2c2dsa
Sample Input 2:
aaabbcddeeeee
Sample Output 2:
a3b2cd2e5*/
public class CompressString {
public static String compressString(String str) {
String answer = "";
if (str.length() == 0) {
return answer;
}
int currentCharCount = 1;
answer += str.charAt(0);
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
currentCharCount++;
} else {
if (currentCharCount > 1) {
answer += currentCharCount;
currentCharCount = 1;
}
answer += str.charAt(i);
}
}
if (currentCharCount > 1) {
answer += currentCharCount;
}
return answer;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.next();
System.out.println(compressString(str));
}
}