php实现字符串反转[首尾交换]


php实现字符串反转,不用strrev,不借用数组方式,时间复杂度度小于O(n)的,首尾交换的那种实现。

php 字符串处理

黑-李舜生 9 years, 3 months ago

 <?php
$str = 'hello world';
$tmp = '';
for($i = strlen($str)-1; $i >= 0; $i--){
    $tmp .= $str{$};
}

echo $tmp;

vic008 answered 9 years, 3 months ago

貌似不存在O(n/2)这种说法,也还是O(n)


 php


 <?php

$str = 'I am Mr.Jing';

// 我去!php中字符串的元素居然是可变的
for ($i=0, $j = strlen($str)-1; $i < $j; $i++, $j--) {
    $tmp = $str[$j];
    $str[$j] = $str[$i];
    $str[$i] = $tmp;
}
// 输出结果
echo $str;

JKyoto answered 9 years, 3 months ago

Your Answer