forked from ashoklathwal/Code-for-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstringCompression.java
36 lines (34 loc) · 975 Bytes
/
stringCompression.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
class stringCompression
{
/* Problem Description:
Compress a given string "aabbbccc" to "a2b3c3"
constraint: in-place compression, no extra space to be used
assumption : output size will not exceed input size..
ex input:"abb" -> "a1b2" buffer overflow.. such inputs will not be given.*/
public static void main(String args[])
{
String str = "aaabbccc";
StringBuffer sb=new StringBuffer();
int count = 1;
int i = 0;
// count continious occurance of eaach character
for(i = 0; i < str.length() - 1; i++)
{
if(str.charAt(i) == str.charAt(i+1))
{
count += 1;
}
else
{
sb.append(str.charAt(i)).append(count);
count = 1;
}
}
// for last character
if(str.charAt(str.length()-2) == str.charAt(str.length()-1))
sb.append(str.charAt(i)).append(count);
else
sb.append(str.charAt(i)).append(1);
System.out.println(sb);
}
}