Given a string in format aabbbcccaaa, encode this in shorter format i.e. a2b3c3a3

Run Length Encoding
Given an input string, write a function that returns the Run Length Encoded string for the input string.
For example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3d1e1x6”.

a) Pick the first character from source string.
b) Append the picked character to the destination string.
c) Count the number of subsequent occurrences of the picked character and append the count to destination string.
d) Pick the next character and repeat steps b) c) and d) if end of string is NOT reached.

// CPP program to implement run length encoding
#include <bits/stdc++.h>
using namespace std;
 
void printRLE(string str)
{
    int n = str.length();
    for (int i = 0; i < n; i++) {
 
        // Count occurrences of current character
        int count = 1;
        while (i < n - 1 && str[i] == str[i + 1]) {
            count++;
            i++;
        }
 
        // Print character and its count
        cout << str[i] << count;
    }
}
 
int main()
{
    string str = "wwwwaaadexxxxxxywww";
    printRLE(str);
    return 0;
}
Output:
w4a3d1e1x6y1w3

// Java program to implement run length encoding
 
public class RunLength_Encoding {
    public static void printRLE(String str)
    {
        int n = str.length();
        for (int i = 0; i < n; i++) {
 
            // Count occurrences of current character
            int count = 1;
            while (i < n - 1 && 
                   str.charAt(i) == str.charAt(i + 1)) {
                count++;
                i++;
            }
 
            // Print character and its count
            System.out.print(str.charAt(i));
            System.out.print(count);
        }
    }
 
    public static void main(String[] args)
    {
        String str = "wwwwaaadexxxxxxywww";
        printRLE(str);
    }
}
Output:
w4a3d1e1x6y1w3

Comments

  1. void printRLE(string str)
    {
    int j =0;
    int count = 1;
    string temp;
    for (int i = 0;i<str.length();i++)
    {
    count = 1;
    while((str[i] == str[i+1])&&(i<str.length()))
    {
    count++; i++;
    }
    temp = temp + string(1, str[i]);
    temp.append(to_string(count));
    }
    cout<<temp<<endl;
    }

    int main()
    {
    string str = "wwwwaaadexxxxxxywww";
    printRLE(str);
    return 0;
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Kth most frequent Character in a given String

[16 Feb 2020] Given an array where every element occurs three times, except one element which occurs only once.

[17 Feb 2020] Given an array of integers, find the nearest smaller number for every element such that the smaller element is on left side.