Online Judge Solutions

Sunday, November 2, 2014

Reverse Words in a String

 
Solution 1:

void 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;
            }
        }
        s = output;
    }

Solution 2:

void 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();
        }
    }

No comments:

Post a Comment