题意:

image.png

解题思路:

  1. 思路:
  2. 1. PHP: 从后往前依次遍历,遇到为空,则截取空后面的字符,同时记录空的下标,以便下次计算;
  3. 2. GO:转成数组,取数组长度的二分之一,前后交换;[a, b, c, d] => [d, c, b a]

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String $s
  4. * @return String
  5. */
  6. function reverseWords($s) {
  7. $s = trim($s);
  8. $s1 = "";
  9. $j = strlen($s);
  10. for ($i = strlen($s); $i > 0; $i--) {
  11. if ($s[$i] === " ") {
  12. $s1 .= substr($s, $i + 1, $j - $i - 1). " ";
  13. while ($s[$i - 1] === ' ') --$i;
  14. $j = $i;
  15. }
  16. }
  17. $s1 .= substr($s, 0, $j);
  18. return $s1;
  19. }
  20. }

GO代码实现:

  1. func reverseWords(s string) string {
  2. s1 := strings.Split(s, " ")
  3. var reverse []string
  4. for i := len(s1)-1; i >= 0; i--{
  5. if s1[i] != ""{
  6. reverse = append(reverse, s1[i])
  7. }
  8. }
  9. return strings.Join(reverse, " ")
  10. }
  11. func rev(s string) string {
  12. s1 := strings.Fields(s)
  13. //前后交换位置
  14. for i := 0; i < len(s1) / 2; i++ {
  15. s1[i], s1[len(s1) - i - 1] = s1[len(s1) - i - 1], s1[i]
  16. }
  17. return strings.Join(s1, " ")
  18. }