6Companies30days

Run Length Encoding

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

If the group’s length is 1, append the character to s. Otherwise, append the character followed by the group’s length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array.

You must write an algorithm that uses only constant extra space.

Example

Input: chars = ["a","a","b","b","c","c","c"]
Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3

Solution

int compress(vector<char>& chars) {
	int l = 0 , r = 0 ;

	for( int r = 0 ; r < chars.size() ; r++ ){
	    int cnt = 1;
	    while( r+1 < chars.size() and chars[r+1] == chars[r] ){
		r++;
		cnt++;
	    }

	    chars[l] = chars[r];
	    l++;
	    if( cnt > 1 ) {
		string count = to_string(cnt);
		for(auto ch : count ){
		    chars[l] = ch;
		    l++;
		}
	    }
	}

	return l;
}