php - Reverse string without strrev -
some time ago during job interview got task reverse string in php without using strrev
.
my first solution this:
$s = 'abcdefg'; $temp = ''; ($i = 0, $length = mb_strlen($s); $i < $length; $i++) { $temp .= $s{$length - $i - 1}; } var_dump($temp); // outputs string(7) "gfedcba"
then asked me if without doubling memory usage (not using $temp
variable or variable copy reversed string to) , failed. kept bugging me , since tried solve multiple times failed.
my latest try looks this:
$s = 'abcdefg'; ($i = 0, $length = mb_strlen($s); $i < $length; $i++) { $s = $s{$i * 2} . $s; } var_dump($s); // outputs string(14) "gfedcbaabcdefg"
it's not solution chop off "abcdefg" after loop because still double amount of memory used. need remove last character in every iteration of loop.
i tried use mb_substr
this:
$s = 'abcdefg'; ($i = 0, $length = mb_strlen($s); $i < $length; $i++) { $s = $s{$i * 2} . mb_substr($s, $length - $i - 1, 1); } var_dump($s);
but gives me uninitialized string offset
errors.
this i'm stuck (again). tried googling solutions found either echo
characters directly or use temporary variable.
i found question php string reversal without using memory there's no answer fits needs.
that's interesting one. here's came with:
$s = 'abcdefghijklm'; for($i=strlen($s)-1, $j=0; $j<$i; $i--, $j++) { list($s[$j], $s[$i]) = array($s[$i], $s[$j]); } echo $s;
list()
can used assign list of variables in 1 operation. doing swapping characters (starting first , last, second-first , second-last , on, till reaches middle of string)
output mlkjihgfedcba
. not using other variables $s
, counters, hope fits criteria.