[LeetCode] Reverse Words in a String II

186. Reverse Words in a String II

Given a character array s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by a single space.

Your code must solve the problem in-place, i.e. without allocating extra space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
void reverseWords(vector<char>& s) {
int n = s.size(), l = 0, r = n - 1;
while(l < r) swap(s[l++], s[r--]);
l = r = 0;
while(r < n) {
while(r < n and s[r] != ' ') r++;
for(int i = l, j = r - 1; i < j; i++, j--) {
swap(s[i], s[j]);
}
l = r = r + 1;
}
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/reverse-words-in-a-string-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.