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
    }
};

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-28
  • 2021-08-21
  • 2021-12-04
  • 2022-02-11
  • 2021-10-01
猜你喜欢
  • 2021-11-24
  • 2022-01-27
  • 2021-07-29
  • 2022-02-04
  • 2022-02-24
  • 2022-12-23
相关资源
相似解决方案