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 @@ -761,6 +761,53 @@ func reverseWord(_ s: inout [Character]) {
761
761
762
762
763
763
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
+ ```
764
811
765
812
766
813
-----------------------
You can’t perform that action at this time.
0 commit comments