Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

557. Reverse Words in a String III 🌟

Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

O(N*M) Time and O(M) Space

O(N*M) Time solution

Code

class Solution {
public:
    string reverseWords(string s) {
        int n = s.size();
        int l=0,r;
        for(int i=0;i<n;i++){
            if(s[i]==' '){
                r=i-1;
                while(l<r){
                    swap(s[l++],s[r--]);
                }
                l=i+1;
            }
        }
        r=n-1;
        while(l<r){
            swap(s[l++],s[r--]);
        }
        return s;
    }
};