给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] 输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:
- 单词的定义是不包含空格的一系列字符
- 输入字符串中不会包含前置或尾随的空格
- 单词与单词之间永远是以单个空格隔开的
进阶:使用 O(1) 额外空间复杂度的原地解法。
先翻转里面每个单词,最后再将字符串整体翻转。
class Solution:
def reverseWords(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
def reverse(s, i, j):
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
i, j, n = 0, 0, len(s)
while j < n:
if s[j] == ' ':
reverse(s, i, j - 1)
i = j + 1
elif j == n - 1:
reverse(s, i, j)
j += 1
reverse(s, 0, n - 1)
class Solution {
public void reverseWords(char[] s) {
int n = s.length;
for (int i = 0, j = 0; j < n; ++j) {
if (s[j] == ' ') {
reverse(s, i, j - 1);
i = j + 1;
} else if (j == n - 1) {
reverse(s, i, j);
}
}
reverse(s, 0, n - 1);
}
private void reverse(char[] s, int i, int j) {
for (; i < j; ++i, --j) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
class Solution {
public:
void reverseWords(vector<char>& s) {
int n = s.size();
for (int i = 0, j = 0; j < n; ++j) {
if (s[j] == ' ') {
reverse(s, i, j - 1);
i = j + 1;
} else if (j == n - 1) {
reverse(s, i, j);
}
}
reverse(s, 0, n - 1);
}
void reverse(vector<char>& s, int i, int j) {
for (; i < j; ++i, --j) {
swap(s[i], s[j]);
}
}
};
func reverseWords(s []byte) {
n := len(s)
for i, j := 0, 0; j < n; j++ {
if s[j] == ' ' {
reverse(s, i, j-1)
i = j + 1
} else if j == n-1 {
reverse(s, i, j)
}
}
reverse(s, 0, n-1)
}
func reverse(s []byte, i, j int) {
for i < j {
s[i], s[j] = s[j], s[i]
i++
j--
}
}