首页 > 代码库 > 【Leetcode】Reverse Words in a String

【Leetcode】Reverse Words in a String

 

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.

 

 1 st ( 20 tries)

class Solution {    vector<string> vs;public:    void reverseWords(string &s)     {        string tmp;        if(s == "")            return;        int start = 0;        while(s[start] == ‘ ‘)            start++;        int end = s.length() - 1;        while(s[end] == ‘ ‘)            end--;        if(start > end)        {            s = "";            return;        }        for(int i = start;i <= end;i++)        {            if(s[i] == ‘ ‘)            {                vs.push_back(tmp);                tmp.clear();                while(s[i+1] == ‘ ‘)                {                    i++;                }            }            else            {                tmp.push_back(s[i]);            }                    }        if(tmp == "")            ;        else            vs.push_back(tmp);        s = "";        for(int i = vs.size() - 1;i > 0;i--)        {            s += vs[i];            s += ‘ ‘;        }        s += vs[0];    }};

  

2 nd ( 4 tries)

class Solution {public:    void reverseWords(string &s) {        int start = 0;        //skip beginning space        while(start < s.length() && s[start] == ‘ ‘)             start++;        int send = s.length() - 1;        //skip end space        while(send >= 0 && s[send] == ‘ ‘)            send--;        //change string s        if(start > send) {            s = "";            return;        }        else            s = s.substr(start,send-start+1);                vector<string> words;        //change mid space to one space        int wordbegin = 0;        for(int i = 0;i < s.length();i++) {            if(s[i] == ‘ ‘) {                words.push_back( s.substr(wordbegin,i-wordbegin) );                while(i < s.length() && s[i] == ‘ ‘)                    i++;                wordbegin = i;            }            if(i == s.length() - 1) {                words.push_back( s.substr(wordbegin,i-wordbegin+1) );            }        }        //combination        s = "";        for(int i = words.size() - 1;i >= 0;i--) {            if(i == 0)                 s += words[i];            else {                s += words[i];                s += " ";            }        }    }};