INPUT :
A string "s" consisting of possibly repeating characters.
E.g. "aaaaabbbcddddefgttt"
OUTPUT :
A string s' such that s'.length() <= s.length(). String shortening is done by counting the contiguous occurrence of the characters and replacing them by the single character and its count of occurrence.
E.g. "a5b3cd4efgt3"
Wikipedia Page
A string "s" consisting of possibly repeating characters.
E.g. "aaaaabbbcddddefgttt"
OUTPUT :
A string s' such that s'.length() <= s.length(). String shortening is done by counting the contiguous occurrence of the characters and replacing them by the single character and its count of occurrence.
E.g. "a5b3cd4efgt3"
Wikipedia Page
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
import java.util.Scanner; | |
public class RunLengthEncoding { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
System.out.println("Enter a string"); | |
String s = in.next(); | |
System.out.println(runLengthEncoding(s)); | |
in.close(); | |
System.exit(0); | |
} | |
public static String runLengthEncoding(String s){ | |
char thisChar; | |
int beginIndex = 0, j = 0, count = 0; | |
for (int i = 0; i < s.length()-1; i++) { | |
thisChar = s.charAt(i); | |
if(thisChar == s.charAt(i+1)){ | |
beginIndex = i; | |
count = 0; | |
//start the traversal | |
for (j = i; j < s.length(); j++) { | |
if(thisChar == s.charAt(j)){ | |
count++; | |
continue; | |
} | |
else{ | |
break; | |
} | |
} | |
//concat the string | |
s = s.substring(0, beginIndex) + s.substring(beginIndex, j-count+1) + count + s.substring(j, s.length()); | |
} | |
} | |
return s; | |
} | |
} |
No comments:
Post a Comment