Leetcode 151 Solution
This article provides solution to leetcode question 151 (reverse-words-in-a-string)
Access this page by simply typing in "lcs 151" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/reverse-words-in-a-string
Solution
class Solution {
public:
void reverseWords(string &s) {
int i = 0;
while (true)
{
auto end = s.find_first_of(' ', i);
if (end == string::npos)
{
reverse(&s[i], &s[s.size()]);
break;
}
else
{
reverse(&s[i], &s[end]);
i = end + 1;
}
}
reverse(s.begin(), s.end());
int l = 0;
for (int i = 0; i < s.size(); i++)
{
if (i == 0 && s[i] == ' ')
continue;
if (i > 0 && s[i - 1] == ' ' && s[i] == ' ')
continue;
s[l++] = s[i];
}
if (l > 0 && s[l - 1] == ' ')
l--;
s[l] = 0;
}
};