Created
January 24, 2016 12:51
-
-
Save rohitvvv/106ce7cb9db114c2d947 to your computer and use it in GitHub Desktop.
CompressDecompress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
public class Main { | |
String str; | |
String compStr; | |
Main(String str){ | |
this.str=str; | |
} | |
//Str => aaaabbcdddddeeeeeeffffghhhhh | |
String compress(){ | |
StringBuffer buff = new StringBuffer(); | |
//buff.append(str.charAt(0)); | |
char c = str.charAt(0); | |
int runningCount=0; | |
runningCount++; | |
//Master loop to compress in O(n) | |
for(int i=1;i<str.length();i++){ | |
//This is an important condition to emit count of last character | |
if(i==str.length()-1) | |
buff.append(c+""+runningCount); | |
else if(str.charAt(i)==c) | |
runningCount++; | |
else{ | |
buff.append(c+""+runningCount); | |
//Reset running count; | |
runningCount=1; | |
} | |
c = str.charAt(i); | |
} | |
return buff.toString(); | |
} | |
String decompress(String compressedString){ | |
int i;int x;x=0; | |
StringBuffer buff = new StringBuffer(); | |
for(i=0;i<compressedString.length();i++) | |
{ | |
char c; | |
int count; | |
c= compressedString.charAt(i); | |
count = Character.getNumericValue(compressedString.charAt(i+1)); | |
while(x<count){ | |
buff.append(c); | |
x++; | |
}x=0; | |
i++; | |
} | |
return buff.toString(); | |
} | |
public static void main(String[] args) { | |
Main obj = new Main("xaaaabbcdddddeeeeeeffffghhhhhassserer"); | |
String str = obj.compress(); | |
System.out.println(str); | |
System.out.println(obj.decompress(str)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment