#include "s0151_reverse_words_in_a_string.hpp" void S0151::reverseSubStr(string &s, int begin, int end) { for (; begin < end; ++begin, --end) { char tmp = s[begin]; s[begin] = s[end]; s[end] = tmp; } } string S0151::reverseWords(string s) { if (s.length() == 0) { return s; } // remove extra spaces int len = s.length(); int slow{0}; for (int fast{0}; fast < len; ++fast) { if (s[fast] != ' ') { s[slow++] = s[fast]; } else { if (fast == len - 1) { break; } else { if (s[fast + 1] != ' ' && slow != 0) { s[slow++] = ' '; } } } } s.resize(slow); // reverse the whole string len = s.length(); reverseSubStr(s, 0, len - 1); // reverse each words for (int begin{0}, end{0}; end < len; ++end) { if (end == len - 1) { reverseSubStr(s, begin, end); } else { if (s[end + 1] == ' ') { reverseSubStr(s, begin, end); begin = end + 2; end = end + 1; } } } return s; }