File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -817,6 +817,53 @@ object Solution {
817
817
```
818
818
819
819
820
+ PHP:
821
+ ``` php
822
+ function reverseWords($s) {
823
+ $this->removeExtraSpaces($s);
824
+ $this->reverseString($s, 0, strlen($s)-1);
825
+ // 将每个单词反转
826
+ $start = 0;
827
+ for ($i = 0; $i <= strlen($s); $i++) {
828
+ // 到达空格或者串尾,说明一个单词结束。进行翻转。
829
+ if ($i == strlen($s) || $s[$i] == ' ') {
830
+ // 翻转,注意是左闭右闭 []的翻转。
831
+ $this->reverseString($s, $start, $i-1);
832
+ // +1: 单词与单词直接有个空格
833
+ $start = $i + 1;
834
+ }
835
+ }
836
+ return $s;
837
+ }
838
+
839
+ // 移除多余空格
840
+ function removeExtraSpaces(& $s){
841
+ $slow = 0;
842
+ for ($i = 0; $i < strlen($s); $i++) {
843
+ if ($s[$i] != ' ') {
844
+ if ($slow != 0){
845
+ $s[$slow++] = ' ';
846
+ }
847
+ while ($i < strlen($s) && $s[$i] != ' ') {
848
+ $s[$slow++] = $s[$i++];
849
+ }
850
+ }
851
+ }
852
+ // 移动覆盖处理,丢弃多余的脏数据。
853
+ $s = substr($s,0,$slow);
854
+ return ;
855
+ }
856
+
857
+ // 翻转字符串
858
+ function reverseString(& $s, $start, $end) {
859
+ for ($i = $start, $j = $end; $i < $j; $i++, $j--) {
860
+ $tmp = $s[$i];
861
+ $s[$i] = $s[$j];
862
+ $s[$j] = $tmp;
863
+ }
864
+ return ;
865
+ }
866
+ ```
820
867
821
868
822
869
-----------------------
You can’t perform that action at this time.
0 commit comments