java Run-length encoding

后端 未结 5 1299
臣服心动
臣服心动 2020-12-06 08:38

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

5条回答
  •  独厮守ぢ
    2020-12-06 09:34

    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 = "aaaabbbccffffdffffddeeffffff";
    
            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;
        }
    
    }
    

提交回复
热议问题