Sample string compression Run length encoding using the travel long encoding example _java

Source: Internet
Author: User

Example: Helloooooo => he2l6o

Copy Code code as follows:

/**
* 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 ();
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.