Reverse Words in a String Total Accepted: 67 Total Submissions: 412My Submissions
Given an input string, reverse the string word by word.
For example,
Given s ="the sky is blue
",
Return"blue is sky the
".
Click to show clarification.
Clarification:
- What constitutes a word?
A sequence of non-space characters constitutes a word.
- Cocould the input string contain leading or trailing spaces?
Yes. However, your reversed string shocould not contain leading or trailing spaces.
- How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Leetcode has not updated the question for a long time. It's a coincidence. Today, I just mentioned that I have fixed 150 questions and I will have a new question.
Okay, paste it as soon as possible.
Ideas:
1. traverse the string from the back
2. Save the word and then reverse it. Save it to the result.
Pay attention to the clarification in the question and handle the spaces.
Two additional strings are used to save the intermediate results. The space complexity is O (n ).
The time complexity is O (n). Simple question: 2 to 3 stars
void reverseWords(string &s){string rs;for (int i = s.length()-1; i >= 0; ){while (i >= 0 && s[i] == ' ') i--;if (i < 0) break;if (!rs.empty()) rs.push_back(' ');string t;while (i >= 0 && s[i] != ' ') t.push_back(s[i--]);reverse(t.begin(), t.end());rs.append(t);}s = rs;}