Pocket Gems interview question

Implement a method to perform basic string compression using the counts of repeated characters. "aabcccc" becomes "2a1b4c".

Interview Answers

Anonymous

13 Feb 2012

#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; }

2

Anonymous

22 Sept 2012

C# private static int countCompression(string str) { int size = 0; char last = str[0]; int count = 1; for (int i = 0; i = str.Length) { return str; } StringBuilder stb = new StringBuilder(); char last = str[0]; int count = 1; for (int i = 1; i = str.Length) { return str; } string result = string.Empty; char last = str[0]; int count = 1; for (int i = 1; i < str.Length; i++) { if (last == str[i]) { count++; } else { result += last.ToString(); result += count.ToString(); last = str[i]; count = 1; } } result += last.ToString(); result += count.ToString(); return result; }

Anonymous

15 Dec 2012

std::string stringcompression(std::string str) { int len = str.length(); std::stringstream ss; std::string outstring=""; char prev='\0'; int i = 0; while(i