Reverse Words in a String My Submissions Question
Total Accepted: 84277 Total Submissions: 546781 Difficulty: Medium
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
click to show clarification.
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
Subscribe to see which companies asked this question
class Solution {
public:
void reverseWords(string &s) {
int len = s.size();
if(!len) return;
int i = 0;
while(s[i] == ' '){
++ i;
}
s.erase(0,i);
i = s.size() - 1;
while(s[i] == ' '){
--i;
}
s.erase(i + 1);
if(s.size() == 0) return;
for(i = 0;i <= s.size() - 1;++ i){
int dis = 0;
if(s[i] == ' ' && i + 1 <= s.size() - 1 && s[i + 1] == ' '){
dis = 1;
while(i + dis + 1 <= s.size() - 1 && s[i + dis + 1] == ' '){
++ dis;
}
s.erase(i + 1,dis);
}
}
reverse(s.begin(),s.end());
for(int b = 0,e = 0;e <= s.size() - 1; ++ e){
if(s[e] == ' ' ){
reverse(s.begin() + b,s.begin() + e);
b = e + 1;
}
else if(e == s.size() - 1){
reverse(s.begin() + b,s.end());
return;
}
}
}
};