Online Judge Solutions

Thursday, December 25, 2014

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".
Example
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:
    string reverseWords(string &s) {
        string output = "";
        int len = 0;
        for(int i = s.length()-1; i >=0; i--)
        {
            if (s[i] != ' ') 
              len++;
          
            if (len > 0 && (i==0 || s[i-1] == ' '))
            {
               if (output.length() >0) output += " ";
               output += s.substr(i, len); 
               len = 0;
            }
        }
        return output;
    }
};


class Solution {
public:
    string reverseWords(string &s) {
       stack<string> st;
        
        string word = "";
        for(char c: s)
        {
            if (c == ' ')
            {
                if (word != "")
                {
                    st.push(word);
                    word = "";
                }
            }
            else 
              word += c;
        }
        
        if (word != "") st.push(word);
       
        s ="";
        if (st.size() >= 1)
        {
            s = st.top();
            st.pop();
        }
            
        while(st.size() > 0)
        {
          s += " " + st.top();
          st.pop();
        }
        return s;
    }
};

No comments:

Post a Comment