题意:

image.png

解题思路:

  1. 1. 将数组整体反转
  2. 2. 再以" " 为边界,单个字符进行反转
  3. 3. 直到末尾[边界条件],最后一个字符,再反转;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String[] $s
  4. * @return NULL
  5. */
  6. function reverseWords(&$s) {
  7. $this->reverse($s, 0, count($s) - 1);
  8. $i = 0;
  9. for ($j = 0; $j < count($s); $j ++) {
  10. if ($s[$j] == ' ') {
  11. $this->reverse($s, $i, $j - 1);
  12. $i = $j + 1;
  13. }
  14. }
  15. $this->reverse($s, $i, count($s) - 1);
  16. }
  17. function reverse(&$arr, $l, $r) {
  18. while ($l < $r) {
  19. $t = $arr[$l];
  20. $arr[$l] = $arr[$r];
  21. $arr[$r] = $t;
  22. $l ++;
  23. $r --;
  24. }
  25. }
  26. }

go代码实现:

  1. func reverseWords(s []byte) {
  2. reverse(s, 0, len(s) - 1)
  3. i := 0
  4. for j := 0; j < len(s);j ++ {
  5. if s[j] == ' ' {
  6. reverse(s, i, j - 1)
  7. i = j + 1
  8. }
  9. }
  10. reverse(s, i, len(s) - 1)
  11. }
  12. func reverse(s []byte, i, j int) {
  13. for i < j {
  14. s[i], s[j] = s[j], s[i]
  15. i++
  16. j--
  17. }
  18. }