题意:
解题思路:
思路:
1. PHP: 从后往前依次遍历,遇到为空,则截取空后面的字符,同时记录空的下标,以便下次计算;
2. GO:转成数组,取数组长度的二分之一,前后交换;[a, b, c, d] => [d, c, b a]
PHP代码实现:
class Solution {
/**
* @param String $s
* @return String
*/
function reverseWords($s) {
$s = trim($s);
$s1 = "";
$j = strlen($s);
for ($i = strlen($s); $i > 0; $i--) {
if ($s[$i] === " ") {
$s1 .= substr($s, $i + 1, $j - $i - 1). " ";
while ($s[$i - 1] === ' ') --$i;
$j = $i;
}
}
$s1 .= substr($s, 0, $j);
return $s1;
}
}
GO代码实现:
func reverseWords(s string) string {
s1 := strings.Split(s, " ")
var reverse []string
for i := len(s1)-1; i >= 0; i--{
if s1[i] != ""{
reverse = append(reverse, s1[i])
}
}
return strings.Join(reverse, " ")
}
func rev(s string) string {
s1 := strings.Fields(s)
//前后交换位置
for i := 0; i < len(s1) / 2; i++ {
s1[i], s1[len(s1) - i - 1] = s1[len(s1) - i - 1], s1[i]
}
return strings.Join(s1, " ")
}