Last active
January 1, 2026 04:47
-
-
Save artlung/b2992e8e763123621df634ccc067f118 to your computer and use it in GitHub Desktop.
replaceRepeats.php: Interview question of the week; https://buttondown.com/cassidoo/archive/the-beginning-is-the-word-and-the-end-is-silence/
This file contains hidden or 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
| /** | |
| * | |
| * Replaces sequences of repeated numeric characters in a string with the length of that sequence. | |
| * | |
| * @param $inputString string A string of numeric characters | |
| * @param $numberToReplaceWithLengthsOf int A single digit (0-9) | |
| * | |
| */ | |
| function replaceRepeats(string $inputString, int $numberToReplaceWithLengthsOf): string | |
| { | |
| $length = strlen($inputString); | |
| $resultString = ''; | |
| $bufferedCountOfRepeats = 0; | |
| for ($i = 0; $i < $length; $i++) { | |
| $currentChar = $inputString[$i]; | |
| $currentChatAsInt = intval($currentChar); | |
| if ($currentChatAsInt === $numberToReplaceWithLengthsOf && $bufferedCountOfRepeats) { | |
| $bufferedCountOfRepeats++; | |
| } elseif ($currentChatAsInt === $numberToReplaceWithLengthsOf && !$bufferedCountOfRepeats) { | |
| $bufferedCountOfRepeats = 1; | |
| } elseif ($currentChatAsInt !== $numberToReplaceWithLengthsOf && $bufferedCountOfRepeats) { | |
| $resultString = $resultString . strval($bufferedCountOfRepeats); | |
| $bufferedCountOfRepeats = 0; | |
| $resultString = $resultString . $currentChar; | |
| } else { | |
| $resultString = $resultString . $currentChar; | |
| } | |
| } | |
| if ($bufferedCountOfRepeats) { | |
| $resultString = $resultString . strval($bufferedCountOfRepeats); | |
| } | |
| return $resultString; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment