-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_compression.java
More file actions
39 lines (32 loc) · 966 Bytes
/
string_compression.java
File metadata and controls
39 lines (32 loc) · 966 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
37
38
39
import java.util.*;
public class string_compression{
public static String compression(String s){
int l=s.length();
StringBuilder n=new StringBuilder("");
for(int i=0;i<l;i++){
int count=1,t=i;
while(s.charAt(i)==s.charAt(t+1)){
count++;
t++;
if(t>l-2){
break;
}
}
if(count==1){
n.append(s.charAt(i));
}
else{
n.append(s.charAt(i));
n.append(count);
}
i=t;
}
return n.toString();
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("enter a string examle 'aaabbbdddfff' : ");
String s=sc.nextLine();
System.out.print("after compression of string is : "+compression(s));
}
}