Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
- 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.
LeetCode上第一题,没注意
Clarification,浪费了些时间:各种“ ” “ a ” “ a” “a ” “ a ” "
the sky is blue
"等都需要考虑
void reverseWords(string &s) {
if(s == "")return;
string s1 = "";
string temp = "";
size_t i = 0;
//去掉前面的空格
while(s[i] == ' ')i++;
while(i < s.length()){
if(s[i] != ' '){
temp += s[i];
}else{
if(s1 == ""){
s1 = temp;
temp = "";
}else{
if(temp!= "")
s1 = temp + " " + s1;
temp = "";
}
}
i++;
}
if(temp != ""){
if(s1 != ""){
s1 = temp + " " + s1;
}else{
s1 = temp;
}
}
s = s1;
}