Skip to content

Latest commit

 

History

History
34 lines (28 loc) · 804 Bytes

reverse-words-in-a-string.md

File metadata and controls

34 lines (28 loc) · 804 Bytes

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;
        }
    };