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

描述

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
    }
};
posted @ 2017-05-17 14:32  larryking  阅读(150)  评论(0编辑  收藏  举报