/**
* Run-length Code (travel long Code)
* @author would
*
*/
public class Runlengthencoder {
public static void Main (string[] args) {
String input = "0";
System.out.println ("Original String Length:" + input.length ());
String encodedstr = encode (input);
SYSTEM.OUT.PRINTLN ("encoded String:" + encodedstr);
SYSTEM.OUT.PRINTLN ("Encoded String Length:" + encodedstr.length ());
String decodedstr = decode (ENCODEDSTR);
System.out.println ("Decoded String:" + decodedstr);
}
/**
* Encode strings with run-length algorithm
* @param sourcestr Original string
* @return
*/
public static string encode (string sourcestr) {
if (sourcestr = null | | sourcestr.length () <= 1) {
return sourcestr;
}
int len = Sourcestr.length ();
StringBuilder Resultbuilder = new StringBuilder ();
for (int i = 0; i < len; i++) {
Char cur = sourcestr.charat (i);
int runlength = 1;
while ((i+1) < Len && Sourcestr.charat (i+1) = = cur) {
i++;
runlength++;
}
if (RunLength > 1) {
Resultbuilder.append (RunLength + "" + cur);
}
else {
Resultbuilder.append (cur);
}
}
return resultbuilder.tostring ();
}
/**
* Decoding RUN-LENGTH encoded strings
* @param encodedstr
* @return
*/
public static string decode (string encodedstr) {
if (encodedstr = null | | encodedstr.length () <= 1) {
return encodedstr;
}
int len = Encodedstr.length ();
StringBuilder Resultbuilder = new StringBuilder ();
for (int i = 0; i < len; i++) {
Char Curchar = Encodedstr.charat (i);
if (Character.isdigit (Curchar)) {
i++;
Char Nextchar = Encodedstr.charat (i);
int runlength = Integer.parseint (Curchar + "");
for (int j = 0; J < RunLength; J + +) {
Resultbuilder.append (Nextchar);
}
}
else {
Resultbuilder.append (Curchar);
}
}
return resultbuilder.tostring ();
}
}