In this Leetcode Reverse Words in a String problem solution, we have Given an input string s, reverse the order of the words. A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space. Return a string of the words in reverse order concatenated by a single space.

Leetcode Reverse Words in a String problem solution


Problem solution in Python.

class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join(s.split()[::-1])



Problem solution in Java.

public class Solution {
    public String reverseWords(String s) {
        String [] words = s.split(" ");
        StringBuilder sb = new StringBuilder();
        int end = words.length - 1;
        for(int i = 0; i<= end; i++){
            if(!words[i].isEmpty()) {
                sb.insert(0, words[i]);
                if(i < end) sb.insert(0, " ");
            }
        }
        return sb.toString();
    }
}


Problem solution in C++.

string reverseWords(string s) {
int n = s.length();
stack<string>st;
string temp ="";
string ans = "";
for(int i =0;i<n;i++)
{
	if(s[i] == ' ')
	{
        if(temp.length() > 0)
             st.push(temp);
        temp ="";
	}
	else
	{
		temp+=s[i];
	}
}

ans+=temp;

while(!st.empty())
{
	ans+= " " + st.top();
	st.pop();
}
if(ans.length() != 0 && ans[0] == ' ') ans=ans.substr(1);
return ans;
}


Problem solution in C.

void reverse(char *start,char *end)
{
    while(end > start)
    {
        char temp = *start;
        *start = *end;
        *end = temp;
        start++,end--;
    }
}

void trim(char *S)
{
    int count = 0;
    int N = strlen(S);
    int flag = 1;
    for(int i=0;i<N;i++)
    {
        if(S[i] != ' ')
        {
            S[count++] = S[i];
            flag = 0;
        }
        else
        {
            if(!flag)
            {
                S[count++] = S[i];
                flag = 1;
            }
        }
    }
    if(count >= 1 && S[count-1] == ' ')
        S[count-1] = '\0';
    else
        S[count] = '\0';
}

void reverseWords(char *S)
{
    trim(S);
    char *temp = S,*prev = S;
    while(*temp)
    {
        temp++;
        if(*temp == ' ')
        {
            reverse(prev,temp-1);
            prev = temp+1;
        }
        else if(*temp == '\0')
        {
            reverse(prev,temp-1);
        }
    }
    reverse(S,temp-1);
}