您的位置:首页 > 其它

leetcode解题报告(25):Reverse Words in a String III

2017-05-17 14:32 645 查看

描述


Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"

Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.


分析

用istringstream来读取string中的每一个word,然后对每一个word通过reverse函数反转。

代码如下:

class Solution {
public:
string reverseWords(string s) {
string word;   //hold every word in the string
string ret;
istringstream ss(s);
while(ss>>word){   //read a word
reverse(word.begin(),word.end());  //reverse it
ret = ret + word + " ";    //splice them
}
return ret.substr(0,ret.size() - 1);   //remove ' ' at end of the string
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: