1.Reverse Words in a String

Question I

Example 1:
Input: "the sky is blue"
Output: "blue is sky the"

Example 2:
Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:
Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Solution:-

class Solution
{
public:
    string reverseWords(string s)
    {
        string str = "";
        string word = "";
        int i = s.length() - 1;
        
        int j=0;
        while(s[j]==32){
            j++;
        }
        while (i >= j)
        {
            if (s[i] != 32)
            {
                word = s[i] + word;
            }

            else if (s[i] == 32 && word != "")
            {
                str = str + word + " ";
                word = "";
            }

            i--;
        }
        str = str + word;

        return str;
    }
};

Time complexity:- O(n) , Space Complexity:- O(n)

Question II

Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Solution:

class Solution {
public:
    string reverseWords(string s) {
        
        if(s==""){return s;}
        
        int i=0;
        string str="",word="";
        while(i<=s.length()-1){
            
            if(s[i]!=32){
                word = s[i]+word;
            }
            else if(s[i]==32 && word!=""){
                str = str + word + " ";
                word = "";
            }
            i++;
        }
        
        str = str+word;
        return str;
        
    }
};

Time complexity: O(n) , Space Complexity: O(n)

Last updated