Created
December 9, 2019 21:42
-
-
Save adrianosferreira/b6b0638c5171aea5d6dca01ca11ff621 to your computer and use it in GitHub Desktop.
Decode String in PHP
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
<?php | |
class Solution { | |
/** | |
* @param String $s | |
* @return String | |
*/ | |
function decodeString($s) { | |
$stack = []; | |
$num = ''; | |
$string = ''; | |
for( $i = 0; $i < strlen($s); $i ++ ) { | |
if ( is_numeric( $s[$i] ) ) { | |
$num .= $s[$i]; | |
} elseif ( ctype_alpha( $s[$i] ) ) { | |
$string .= $s[$i]; | |
} elseif ( $s[$i] === '[' ) { | |
$stack[] = [ 'num' => $num, 'string' => $string ]; | |
$num = ''; | |
$string = ''; | |
} else { | |
$val = array_pop( $stack ); | |
$newString = ''; | |
for( $j = 0; $j < (int) $val['num']; $j ++ ) { | |
$newString .= $string; | |
} | |
$string = $val['string'] . $newString; | |
} | |
} | |
return $string; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment