-
Notifications
You must be signed in to change notification settings - Fork 33
/
Problem_06.java
66 lines (63 loc) · 1.79 KB
/
Problem_06.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Cracking-The-Coding-Interview
* Problem_06.java
*/
package com.deepak.ctci.Ch01_Arrays_And_Strings;
/**
* <br> Problem Statement :
*
* Implement a method to perform basic string compression
* using the count of repeated characters. For ex. the string
* "aabcccccaaa" would become "a2b1c5a3". If the sum compressed string
* does not become smaller then the original string, then your
* method should return the original string. You can assume that
* the string has only upper case and lower case letters.
*
* </br>
*
* @author Deepak
*/
public class Problem_06 {
/**
* Method to compress a string
*
* Time Complexity : O(n)
* Space Complexity : O(n)
*
* @param input
* @return {@link String}
*/
public static String compressString(String input) {
/* If input is null, no further processing required */
if (input == null) {
return null;
}
StringBuilder builder = new StringBuilder();
/* Initialize current character and count */
char currentChar = 0;
int count = 1;
for (int i = 0; i < input.length() - 1; i++) {
/* Find current character and check with next character.
* If matches, increase the count else append the character
* and count. Reset the counter. */
currentChar = input.charAt(i);
if (currentChar != input.charAt(i + 1)) {
builder.append(currentChar);
builder.append(count);
count = 1;
} else {
count++;
}
}
/* There is no append happening for last set of characters,
* because if condition won't be true. Appending them here. */
builder.append(currentChar);
builder.append(count);
/* if builder's length is less as compared to
* input, return builder's string else return input */
if (builder.toString().length() < input.length()) {
return builder.toString();
}
return input;
}
}