java Run-length encoding

放肆的年华 提交于 2019-11-30 07:53:52

问题


I have no idea how to start my assignment.

We got to make a Run-length encoding program,

for example, the users enters this string:

aaaaPPPrrrrr

is replaced with

4a3P5r

Can someone help me get started with it?


回答1:


Hopefully this will get you started on your assignment:

The fundamental idea behind run-length encoding is that consecutively occurring tokens like aaaa can be replaced by a shorter form 4a (meaning "the following four characters are an 'a'"). This type of encoding was used in the early days of computer graphics to save space when storing an image. Back then, video cards supported a small number of colors and images commonly had the same color all in a row for significant portions of the image)

You can read up on it in detail on Wikipedia

http://en.wikipedia.org/wiki/Run-length_encoding

In order to run-length encode a string, you can loop through the characters in the input string. Have a counter that counts how many times you have seen the same character in a row. When you then see a different character, output the value of the counter and then the character you have been counting. If the value of the counter is 1 (meaning you only saw one of those characters in a row) skip outputting the counter.




回答2:


public String runLengthEncoding(String text) {
    String encodedString = "";

    for (int i = 0, count = 1; i < text.length(); i++) {
        if (i + 1 < text.length() && text.charAt(i) == text.charAt(i + 1))
            count++;
        else {
            encodedString = encodedString.concat(Integer.toString(count))
                    .concat(Character.toString(text.charAt(i)));
            count = 1;
        }
    }
    return encodedString;
}

Try this one out.




回答3:


This can easily and simply be done using a StringBuilder and a few helper variables to keep track of how many of each letter you've seen. Then just build as you go.

For example:

static String encode(String s) {
    StringBuilder sb = new StringBuilder();
    char[] word = s.toCharArray();
    char current = word[0]; // We initialize to compare vs. first letter

           // our helper variables
    int index = 0; // tracks how far along we are
    int count = 0; // how many of the same letter we've seen

    for (char c : word) {
        if (c == current) {
            count++;
            index++;

            if (index == word.length)
                sb.append(current + Integer.toString(count));
        }

        else {
            sb.append(current + Integer.toString(count));
            count = 1;
            current = c;
            index++;
        }
    }
    return sb.toString();
}

Since this is clearly a homework assignment, I challenge you to learn the approach and not just simply use the answer as the solution to your homework. StringBuilders are very useful for building things as you go, thus keeping your runtime O(n) in many cases. Here using a couple of helper variables to track where we are in the iteration "index" and another to keep count of how many of a particular letter we've seen "count", we keep all necessary info for building our encoded string as we go.




回答4:


import java.util.Scanner;
/**
 * @author jyotiv
 *
 */
 public class RunLengthEncoding {
 /**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter line to encode:");
    Scanner s=new Scanner(System.in);
    String input=s.nextLine();
            int len = input.length();
            int i = 0;
            int noOfOccurencesForEachChar = 0;
            char storeChar = input.charAt(0);

            String outputString = "";
            for(;i<len;i++)
            {
                if(i+1<len)
                {
                    if(input.charAt(i) == input.charAt(i+1))
                    {
                        noOfOccurencesForEachChar++;
                    }
                    else
                    {
                        outputString = outputString + 
   Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
                        noOfOccurencesForEachChar = 0;
                        storeChar = input.charAt(i+1);
                    }
                }
                else
                {
                    outputString = outputString + 
 Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
                }
            }

            System.out.println("Encoded line is: " + outputString);   

        }

}

I have tried this one. It will work for sure.




回答5:


For example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6”.

Source Code (Java):-

package com.algo.runlengthencoding;


public class RunlengthEncoding 
{

    // For example, if the input string is “wwwwaaadexxxxxx”,
    // then the function should return “w4a3d1e1x6”.

    public static void main(String args[]) {

        String str = "aaaabbbccdddddddeeffffff";

        String value = getRunLengthEncodingForGivenString(str);
        System.out.println(value);
    }

    public static String getRunLengthEncodingForGivenString(String str) {
        String value = "", compare = "";

        for (int i = 0; i < str.length(); i++) {
            CharSequence seq = str.charAt(i) + "";

            if (compare.contains(seq))
                continue;

            compare = compare + str.charAt(i);

            int count = 0;
            for (int j = 0; j < str.length(); j++) {
                if (str.charAt(i) == str.charAt(j))
                    count = count + 1;
            }

            value = value + str.charAt(i) + Integer.toString(count);
        }
        return value;
    }

}


来源:https://stackoverflow.com/questions/11442162/java-run-length-encoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!