Given an input string, reverse the string word by word.spa
For example,
Given s = "the sky is blue
",
return "blue is sky the
".code
Clarification:blog
Answer:ip
void re(int start, int end, string &s) { int n = end - start + 1; for (int i = start; i < start + n / 2; i++) { char c = s[i]; s[i] = s[end - i + start]; s[end - i + start] = c; } } void reverseWords(string &s) { int n = s.length(); int flag = 1; int start = 0; int end = 0; re(0, n - 1, s); if (n == 1) { if (s[0] == ' ') { s = s.substr(0, 0); } } else { for (int i = 0; i < n; i++) { if (s[i] == ' ') { if (flag == 0) { re(start, end - 1, s); s[end] = ' '; start = ++end; } flag = 1; } else { s[end++] = s[i]; flag = 0; } } if (start != end) { re(start, end - 1, s); } s = s.substr(0, end); if (s[end - 1] == ' ') { s = s.substr(0, end - 1); } } }