Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) throws Exception {
- Scanner kb = new Scanner(System.in);
- System.out.println("Input: ");
- String str = kb.nextLine();
- String Encoded = "";
- char ch=0;
- char oldCh=0;
- int count=0;
- int index=0;
- // Loop though the entire string
- while (index < str.length()) {
- // Grab next character and save it twice
- ch = str.charAt(index);
- // Set run length to 1
- count=1;
- // Look ahead (if possible)
- if ((index+1) < str.length()) {
- // Save for comparison
- oldCh = ch;
- // Bump index
- index++;
- // Fetch next character
- ch = str.charAt(index);
- // Calculate run length
- while ((ch == oldCh) && (index < str.length())) {
- count++; // Bump count
- index++; // Bump index
- ch = str.charAt(index); // Grab next char
- // NOTE: Most run length encoding algorithms use
- // a maximum run length, so I'll just toss this in there
- // https://en.wikipedia.org/wiki/Run-length_encoding
- if (count > 255) {
- throw new Exception("Exceeded maximum run length (255)");
- }
- }
- // Back up, and regurgitate the look ahead character
- index--;
- ch = oldCh;
- }
- // Emit run length only if required
- if (count > 1) {
- Encoded += count;
- }
- // Emit character
- Encoded += ch;
- // Move to next index
- index++;
- }
- System.out.println("Encoded: " + Encoded);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement