Home > Backend Development > PHP Tutorial > 字符串处理 - php实现字符串反转[首尾交换]

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

WBOY
Release: 2016-06-06 20:38:07
Original
1908 people have browsed it

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

回复内容:

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

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

echo $tmp;
</code>
Copy after login

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

<code>php</code><code><?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;
</code></code>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template