您的位置:首页 > 其它

Reverse Words in a String[LeetCode]

2014-03-15 13:02 417 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

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.
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Reverse Words in a S