题意:
解题思路:
1. 将数组整体反转
2. 再以" " 为边界,单个字符进行反转
3. 直到末尾[边界条件],最后一个字符,再反转;
PHP代码实现:
class Solution {
/**
* @param String[] $s
* @return NULL
*/
function reverseWords(&$s) {
$this->reverse($s, 0, count($s) - 1);
$i = 0;
for ($j = 0; $j < count($s); $j ++) {
if ($s[$j] == ' ') {
$this->reverse($s, $i, $j - 1);
$i = $j + 1;
}
}
$this->reverse($s, $i, count($s) - 1);
}
function reverse(&$arr, $l, $r) {
while ($l < $r) {
$t = $arr[$l];
$arr[$l] = $arr[$r];
$arr[$r] = $t;
$l ++;
$r --;
}
}
}
go代码实现:
func reverseWords(s []byte) {
reverse(s, 0, len(s) - 1)
i := 0
for j := 0; j < len(s);j ++ {
if s[j] == ' ' {
reverse(s, i, j - 1)
i = j + 1
}
}
reverse(s, i, len(s) - 1)
}
func reverse(s []byte, i, j int) {
for i < j {
s[i], s[j] = s[j], s[i]
i++
j--
}
}