Reverse words in a given string | Practice | GeeksforGeeks

Given a String S, reverse the string without reversing its individual words. Words are separated by dots.
Example 1:
Input:
S = i.like.this.program.very.much
Output: much.very.program.this.like.i
Explanation: After reversing the whole
string(not individual words), the input
string becomes
much.very.program.this.like.i

Example 2:
Input:
S = pqr.mno
Output: mno.pqr
Explanation: After reversing the whole
string , the input string becomes
mno.pqr


Your Task:
You dont need to read input or print anything. Complete the function reverseWords() which takes string S as input parameter and returns a string containing the words in reversed order. Each word in the returning string should also be separated by '.' 

Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(|S|)

Constraints:
1 <= |S| <= 2000
 
0
akash22bhin 5 hours
string reverseWords(string S)    {        // code here        string S2;       int r;       int len=S.length();       for(int i=len-1;i>=0;i--)       {           if(S[i]=='.')           {               r=len-i;               len=i-1;               S2.append(S.substr(i+1,r));               S2.append(".");           }       }       S2.append(S.substr(0,len+1));       return S2;   } 
0
yashodeep3113 hours ago
Python Solution:
class Solution:    #Function to reverse words in a given string.   def reverseWords(self,S):       # code here       my_list=list(S.split("."))       return ".".join(my_list[::-1])
0
shivamtiwaritiwari070417 hours ago
string reverseWords(string S)    {       int i;      string res="";      stack<string> st;      for(i=0;i<S.size();i++)      {                  if(S[i]=='.')          {              st.push(res);              res="";          }          else          res+=S[i];      }      st.push(res);      string ans="";      while(!st.empty())      {         ans+=st.top();         ans+=".";         st.pop();      }     ans.pop_back();      return ans;   } 
0
amarrajsmart19721 hours ago
 string reverseWords(string S)    {        // code here        vector<string> v;       string res,ans;       for(int i=0;i<S.length();i++)       {           if(S[i]!='.')           {               ans+=S[i];           }           else           {               v.push_back(ans);               ans="";           }       }       v.push_back(ans);       reverse(v.begin(),v.end());       for(int k=0;k<v.size();k++)       {           res+=v[k];           if(k!=v.size()-1)           res+='.';       }       return res;          } 
0
ashishg6273 days ago
    In javascript      
     var  fields = s.split('.');            var data="";       for(let i=(fields.length)-1;i>=0;i--){           if(i>0){            data= data+fields[i]+".";              }else{               data= data+fields[i];           }              }       return data;
0
sunghunet3 days ago
string reverseWords(string S) 
{ 
    stack<string> stk;
    string str;
    S += ".";
    for (int i = 0; i < S.length(); i++)
    {
        char c = S[i];
        if (c == '.')
        {
            stk.push(str);
            str = "";
        }
        else
            str.push_back(c);
    }

    string res;
    int i = 0;
    while (!stk.empty())
    {
        if (i != 0)
            res += "." + stk.top();
        else
            res += stk.top();

        stk.pop();
        i++;
    }

    return res;
} 
0
muneeralam3206 days ago
PYTHON SOLUTION
def reverseWords(self,S):
        # code here
        s = S.split(".")
        return ".".join(s[::-1])
0
rajanithinbatchu6 days ago
def reverseWords(self,S):
        s=S.split(".")
        b=""
        for i in range(len(s)-1,-1,-1):
            if i>0:
                b+=s[i]+"."
            else:
                b+=s[i]
        return b
0
jayesh291 week ago
JAVA 0.6
    String reverseWords(String S){
       StringBuilder sb = new StringBuilder(S.length());
       int l = S.length();
       for(int i = S.length() - 1; i>-1; --i) {
           if(S.charAt(i) == '.') {
               sb.append(S.substring(i+1, l));
               if(i!=-1){
                  sb.append('.');
               }
               l = i;
           }
       }
       sb.append(S.substring(0, l));
       return sb.toString();
    }
0
ayushayush5911 week ago
string reverseWords(string S)    {              int k = 0;       int n = S.length();       char s1[n];       for(int i =n-1;i>=-1;i--)       {           if(S[i] == '.' || i==-1)           {                 int j = i+1;               while(S[j] != '.' && j != n)               {                   s1[k++] = S[j];                   j++;               }               if(i!=-1)                   s1[k++] = '.';           }       }       s1[k++] = '\0';       return s1;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.