Reverse Words in a String III

2017/12/4 posted in  leetcode

class Solution {
public:
    string reverseWords(string s) {
        string res;
        int str = 0;
        for (int i=0; i<s.length(); i++) {
            if (s[i]==' '||i==s.length()-1) {
                int j = i==s.length()-1 ? i:i-1;
                while (j>=str) {
                    char tmp = s[str];
                    s[str] = s[j];
                    s[j] = tmp;
                    j--;
                    str++;
                }
                str = i+1;
            }
        }

        return s;
    }
};