Reverse Words in a String

来源:互联网 发布:嵌入式需要mac 编辑:程序博客网 时间:2024/06/05 03:39

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

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

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) {        int len = s.size();    int begin=0,end=0;    int n=0;    string s1;    while(end!=len){    begin=s.find_first_not_of(" ",end);       if(begin==-1)    break;    end=s.find_first_of(" ",begin);    if(end==-1)    end=len;    n++;    s1=s.substr(begin,end-begin)+" "+s1;    if(n==1) s1.erase(s1.size()-1,1);    }    s=s1;    }};


0 0
原创粉丝点击