151. Reverse Words in a String
https://leetcode.com/problems/reverse-words-in-a-string/description/
/*
* @lc app=leetcode id=151 lang=cpp
*
* [151] Reverse Words in a String
*/
// @lc code=start
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(), s.end());
int l = -1, r = 0, N = s.length();
while (r < N && s[r] == ' ') {
++r;
}
while (N > 0 && s[N - 1] == ' ') {
--N;
}
while (r < N) {
if (l == -1 && s[r] != ' ') l = r;
if ((r < N - 1 && s[r + 1] != ' ') || (l == -1 && s[r] == ' ')) {
++r;
continue;
}
int tr = r;
while (l < r) {
swap(s[l++], s[r--]);
}
r = tr + 1;
l = -1;
}
l = r = 0;
while (r < N && s[r] == ' ') {
++r;
}
while (r < N) {
if (s[r] == ' ' && (r < N - 1 && s[r + 1] == ' ')) {
++r;
continue;
}
s[l++] = s[r++];
}
while (l > 0 && s[l - 1] == ' ') {
--l;
}
return s.substr(0, l);
}
};
// @lc code=end
Last updated