Created
March 30, 2018 07:09
-
-
Save frag-o-matic/2094c536b8ac610b33a86c4b258aa8d5 to your computer and use it in GitHub Desktop.
Week 1 Kata : String Compression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Problem for week 1: String Compression | |
Implement a method to perform string compression using counts of repeated characters. String "aabccdaaaaa" becomes "a2b1c2d1a5". The function needs to check for errors and raise an error in case - | |
1. resultant compressed string is larger | |
2. invalid character is found. | |
The only valid characters fall into [a-zA-Z] range. | |
*/ | |
#include <iostream> | |
#include <string> | |
#include <sstream> | |
using namespace std; | |
string compress(const std::string& input) | |
{ | |
stringstream resp; | |
if(input.empty()) | |
throw "input string empty"; | |
for(auto i = 0 ; i < input.size() ; ) | |
{ | |
if(!isalpha(input[i])) | |
throw "invalid characters in string"; | |
auto curr_pos = i + 1; | |
while((curr_pos < input.size()) && (input[i] == input[curr_pos])) | |
++curr_pos; | |
auto rep_cnt = curr_pos - i; | |
resp << input[i] << rep_cnt; | |
i += (rep_cnt > 1) ? rep_cnt : 1; | |
} | |
return resp.str(); | |
} | |
int main() | |
{ | |
string input = "aabccdaaaaa"; | |
try | |
{ | |
auto comp = compress(input); | |
if(comp.size() > input.size()) | |
throw "compressed version longer than input"; | |
cout<<"Input String is: "<<input<<endl; | |
cout<<"Compressed String is: "<<comp<<endl; | |
} | |
catch(const char* ex) | |
{ | |
cout<<"Error: "<<ex<<endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment