Reverse Words in a String

来源:互联网 发布:易语言手机版远控源码 编辑:程序博客网 时间:2024/04/30 11:26

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

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:    void reverseWords(string &s){        string res;size_t found1 = 0;while(1){found1 = s.find_first_not_of(' ', found1);if (found1 == string::npos)break;size_t found2 = s.find_first_of(' ', found1);if (!res.empty())res = ' ' + res;if (found2 == string::npos){res  = s.substr(found1) + res;break;}res  = s.substr(found1, found2 - found1) + res;found1 = found2;} s = res;    }};






0 0