Skip to content

Commit 591cf19

Browse files
committed
添加(0151.翻转字符串里的单词.md):PHP版本
1 parent b78e750 commit 591cf19

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

problems/0151.翻转字符串里的单词.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,53 @@ func reverseWord(_ s: inout [Character]) {
761761

762762

763763

764+
PHP:
765+
```php
766+
function reverseWords($s) {
767+
$this->removeExtraSpaces($s);
768+
$this->reverseString($s, 0, strlen($s)-1);
769+
// 将每个单词反转
770+
$start = 0;
771+
for ($i = 0; $i <= strlen($s); $i++) {
772+
// 到达空格或者串尾,说明一个单词结束。进行翻转。
773+
if ($i == strlen($s) || $s[$i] == ' ') {
774+
// 翻转,注意是左闭右闭 []的翻转。
775+
$this->reverseString($s, $start, $i-1);
776+
// +1: 单词与单词直接有个空格
777+
$start = $i + 1;
778+
}
779+
}
780+
return $s;
781+
}
782+
783+
// 移除多余空格
784+
function removeExtraSpaces(&$s){
785+
$slow = 0;
786+
for ($i = 0; $i < strlen($s); $i++) {
787+
if ($s[$i] != ' ') {
788+
if ($slow != 0){
789+
$s[$slow++] = ' ';
790+
}
791+
while ($i < strlen($s) && $s[$i] != ' ') {
792+
$s[$slow++] = $s[$i++];
793+
}
794+
}
795+
}
796+
// 移动覆盖处理,丢弃多余的脏数据。
797+
$s = substr($s,0,$slow);
798+
return ;
799+
}
800+
801+
// 翻转字符串
802+
function reverseString(&$s, $start, $end) {
803+
for ($i = $start, $j = $end; $i < $j; $i++, $j--) {
804+
$tmp = $s[$i];
805+
$s[$i] = $s[$j];
806+
$s[$j] = $tmp;
807+
}
808+
return ;
809+
}
810+
```
764811

765812

766813
-----------------------

0 commit comments

Comments
 (0)