Coding-Interview-101

Solutions to LeetCode problems filtered with companies, topics and difficulty.

View project on GitHub

Reverse Words in a String


Solution


    class Solution {
    public:
        string reverseWords(string s) {
            int i = s.length() - 1;
            string ans = "";
            while(i >= 0 && s[i] == ' ')
                i--;
            for(; i >= 0; ){
                string temp = "";
                while(i >= 0 && s[i] != ' ') {
                    temp = s[i] + temp;
                    i--;
                }
                while(i >= 0 && s[i] == ' ')
                    i--;
                ans += temp;
                if(i >= 0)
                    ans += ' ';
            }
            return ans;
        }
    };