"<small><i>This notebook was prepared by [hashhar](https://github.com/hashhar). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).</i></small>"
"## Problem: Compress a string such that 'AAABCCDDDD' becomes 'A3BCCD4'. Only compress the string if it saves space.\n",
"\n",
"* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n",
"* [Algorithm](#Algorithm)\n",
"* [Code](#Code)\n",
"* [Unit Test](#Unit-Test)"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Constraints\n",
"\n",
"* Can we assume the string is ASCII?\n",
" * Yes\n",
" * Note: Unicode strings could require special handling depending on your language\n",
"* Can you use additional data structures? \n",
" * Yes\n",
"* Is this case sensitive?\n",
" * Yes"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Test Cases\n",
"\n",
"* None -> None\n",
"* '' -> ''\n",
"* 'AABBCC' -> 'AABBCC'\n",
"* 'AAABCCDDDD' -> 'A3BCCD4'"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Algorithm\n",
"\n",
"Since Python strings are immutable, we'll use a list of characters to build the compressed string representation. We'll then convert the list to a string.\n",
"\n",
"* Calculate the size of the compressed string\n",
" * Note the constraint about compressing only if it saves space\n",
"* If the compressed string size is >= string size, return string\n",
"* Create compressed_string\n",
" * For each char in string\n",
" * If char is the same as last_char, increment count\n",
" * Else\n",
" * If the count is more than 2\n",
" * Append last_char to compressed_string\n",
" * append count to compressed_string\n",
" * count = 1\n",
" * last_char = char\n",
" * If count is 1\n",
" * Append last_char to compressed_string\n",
" * count = 1\n",
" * last_char = char\n",
" * If count is 2\n",
" * Append last_char to compressed_string\n",
" * Append last_char to compressed_string once more\n",