Implement a method to perform basic string compression using the counts of repeated characters. "aabcccc" becomes "2a1b4c".
Anonymous
#include #include using namespace std; string &stringcompress(string input ) { string output ; int size = input.length() ; int length = 1 ; char currentChar = input[0] ; if(size == 1) { output.push_back('0'); output.push_back(currentChar) ; } for (int i = 1 ; i < size ;i++) { if( input[i] != currentChar ) { char ptr[1024] ; sprintf(ptr, "%d", length); output.append(ptr); output.push_back(currentChar) ; length = 1 ; currentChar = input[i] ; } else { length ++ ; } if( i == (size -1) ) { char ptr[1024] ; sprintf(ptr, "%d", length); output.append(ptr); output.push_back(currentChar); } } return output; }
Check out your Company Bowl for anonymous work chats.