Tags


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

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

//solution which uses stack

class Solution {
public:
    void reverseWords(string &s) 
    {
        if(s.empty())
            return;
        stack<string> stk;
        size_t i=0;
        char d = ' ';
        size_t j = 0;
        for(; j<s.length(); j++)
        {
            char c = s[j];
            if(c==d)
            {
                if(i!=j)
                    stk.push(s.substr(i,j-i));
                i = j+1;
            }
        }
        if(i!=j)
            stk.push(s.substr(i,j-i));
        
        s.clear();
        while(!stk.empty())
        {
            if(s.empty())
                s = stk.top();
            else
                s = s + d + stk.top();
            stk.pop();
        }
        return;
    }
};
Advertisements