comments | difficulty | edit_url | tags | ||
---|---|---|---|---|---|
true |
中等 |
|
给你一个字符数组 s
,反转其中 单词 的顺序。
单词 的定义为:单词是一个由非空格字符组成的序列。s
中的单词将会由单个空格分隔。
必须设计并实现 原地 解法来解决此问题,即不分配额外的空间。
示例 1:
输入:s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] 输出:["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
示例 2:
输入:s = ["a"] 输出:["a"]
提示:
1 <= s.length <= 105
s[i]
可以是一个英文字母(大写或小写)、数字、或是空格' '
。s
中至少存在一个单词s
不含前导或尾随空格- 题目数据保证:
s
中的每个单词都由单个空格分隔
我们可以遍历字符数组
时间复杂度
class Solution:
def reverseWords(self, s: List[str]) -> None:
def reverse(i: int, j: int):
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
i, n = 0, len(s)
for j, c in enumerate(s):
if c == " ":
reverse(i, j - 1)
i = j + 1
elif j == n - 1:
reverse(i, j)
reverse(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) {
auto reverse = [&](int i, int j) {
for (; i < j; ++i, --j) {
swap(s[i], s[j]);
}
};
int n = s.size();
for (int i = 0, j = 0; j < n; ++j) {
if (s[j] == ' ') {
reverse(i, j - 1);
i = j + 1;
} else if (j == n - 1) {
reverse(i, j);
}
}
reverse(0, n - 1);
}
};
func reverseWords(s []byte) {
reverse := func(i, j int) {
for ; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
i, n := 0, len(s)
for j, c := range s {
if c == ' ' {
reverse(i, j-1)
i = j + 1
} else if j == n-1 {
reverse(i, j)
}
}
reverse(0, n-1)
}
/**
Do not return anything, modify s in-place instead.
*/
function reverseWords(s: string[]): void {
const n = s.length;
const reverse = (i: number, j: number): void => {
for (; i < j; ++i, --j) {
[s[i], s[j]] = [s[j], s[i]];
}
};
for (let i = 0, j = 0; j <= n; ++j) {
if (s[j] === ' ') {
reverse(i, j - 1);
i = j + 1;
} else if (j === n - 1) {
reverse(i, j);
}
}
reverse(0, n - 1);
}