您的位置:首页 > 编程语言 > C语言/C++

[Lintcode]Reverse Words in a String

2016-03-22 17:05 375 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

Have you met this question in a real interview? 

Yes

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.
class Solution {
public:
/**
* @param s : A string
* @return : A string
*/
string reverseWords(string s) {
// write your code here
string res="";
int len=s.size();
int start=0;
while(start<len) {
while(s[start]==' ')
start++;
if(start>=len) break; //注意后置0
int index=-1;
index=s.find(" ",start);
string tmp;
if(index==-1) index=len;
tmp=s.substr(start,index-start);
if(res.size()==0) res=tmp;
else res=tmp+" "+res;
start=index+1;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode