Created
July 16, 2019 11:34
-
-
Save sharifbdp/aa340d958c53d03119e1841bb4636110 to your computer and use it in GitHub Desktop.
Implement a method to perform basic string compression using the counts of repeated/consecutive characters. Such as, the string "aaabbbccd" would become a3b3c2d1. If the compressed converted string does not become smaller than the original string, please return the original string.
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
<?php | |
/** | |
Implement a method to perform basic string compression using the counts of repeated/consecutive characters. Such as, the string "aaabbbccd" would become a3b3c2d1. If the compressed converted string does not become smaller than the original string, please return the original string. | |
**/ | |
function compress_string($word) { | |
$word = strtolower($word); | |
$compressed_word = ""; | |
$prev_letter = ""; | |
$count = 0; | |
for ($i = 0; $i < strlen($word); $i++) { | |
$curr_letter = substr($word, $i, 1); | |
if ($curr_letter == $prev_letter) { | |
$count++; | |
} else { | |
if ($count > 0) { | |
$compressed_word .= ($prev_letter . $count); | |
} | |
$prev_letter = $curr_letter; | |
$count = 1; | |
} | |
} | |
$compressed_word .= ($prev_letter . $count); | |
if (strlen($compressed_word) < strlen($word)) { | |
return $compressed_word; | |
} else { | |
return $word; | |
} | |
} | |
echo compress_string('aaabbbccd'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment