Reverse words in a given string
Last Updated :
13 Sep, 2023
Given a string, the task is to reverse the order of the words in the given string.
Examples:
Input: s = “geeks quiz practice code”
Output: s = “code practice quiz geeks”
Input: s = “i love programming very much”
Output: s = “much very programming love i”
Approach:
- Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
- Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.
Follow the below steps to solve the problem:
- Run a for loop to traverse the string and create a temporary string to store the words
- If the current character is a space then add the current string to the answer and empty the string
- Else push the character into the string
- Print the answer array in reverse order
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void reverseWords(string s)
{
vector<string> tmp;
string str = "" ;
for ( int i = 0; i < s.length(); i++) {
if (s[i] == ' ' ) {
tmp.push_back(str);
str = "" ;
}
else
str += s[i];
}
tmp.push_back(str);
int i;
for (i = tmp.size() - 1; i > 0; i--)
cout << tmp[i] << " " ;
cout << tmp[0] << endl;
}
int main()
{
string s = "i like this program very much" ;
reverseWords(s);
return 0;
}
|
C
#include <stdio.h>
void reverse( char * begin, char * end)
{
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
void reverseWords( char * s)
{
char * word_begin = s;
char * temp = s;
while (*temp) {
temp++;
if (*temp == '\0' ) {
reverse(word_begin, temp - 1);
}
else if (*temp == ' ' ) {
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}
reverse(s, temp - 1);
}
int main()
{
char s[] = "i like this program very much" ;
char * temp = s;
reverseWords(s);
printf ( "%s" , s);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void reverse( char str[], int start, int end)
{
char temp;
while (start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static char [] reverseWords( char [] s)
{
int start = 0 ;
for ( int end = 0 ; end < s.length; end++) {
if (s[end] == ' ' ) {
reverse(s, start, end);
start = end + 1 ;
}
}
reverse(s, start, s.length - 1 );
reverse(s, 0 , s.length - 1 );
return s;
}
public static void main(String[] args)
{
String s = "i like this program very much " ;
char [] p = reverseWords(s.toCharArray());
System.out.print(p);
}
}
|
Python3
def reverse_word(s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start = start + 1
end - = 1
s = "i like this program very much"
s = list (s)
start = 0
while True :
try :
end = s.index( ' ' , start)
reverse_word(s, start, end - 1 )
start = end + 1
except ValueError:
reverse_word(s, start, len (s) - 1 )
break
s.reverse()
s = "".join(s)
print (s)
|
C#
using System;
class GFG {
static void reverse( char [] str, int start, int end)
{
char temp;
while (start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static char [] reverseWords( char [] s)
{
int start = 0;
for ( int end = 0; end < s.Length; end++) {
if (s[end] == ' ' ) {
reverse(s, start, end);
start = end + 1;
}
}
reverse(s, start, s.Length - 1);
reverse(s, 0, s.Length - 1);
return s;
}
public static void Main(String[] args)
{
String s = "i like this program very much " ;
char [] p = reverseWords(s.ToCharArray());
Console.Write(p);
}
}
|
Javascript
<script>
function reverse(str,start,end)
{
let temp;
while (start <= end)
{
temp = str[start];
str[start]=str[end];
str[end]=temp;
start++;
end--;
}
}
function reverseWords(s)
{
s=s.split( "" );
let start = 0;
for (let end = 0; end < s.length; end++)
{
if (s[end] == ' ' )
{
reverse(s, start, end);
start = end + 1;
}
}
reverse(s, start, s.length - 1);
reverse(s, 0, s.length - 1);
return s.join( "" );
}
var s = "i like this program very much " ;
document.write(reverseWords(s));
</script>
|
Output
much very program this like i
Time complexity: O(N)
Auxiliary Space: O(N)
Note: The above code doesn’t handle the cases when the string starts with space.
Below is the implementation of the approach that handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version.
C++
#include <bits/stdc++.h>
using namespace std;
void reverse(string& s, int begin, int end)
{
while (begin < end) {
swap(s[begin++], s[end--]);
}
}
void reverseWords(string& s)
{
int word_begin = -1;
int i = 0;
while (i < s.size()) {
if ((word_begin == -1) && (s[i] != ' ' )) {
word_begin = i;
}
if (word_begin != -1
&& ((s[i + 1] == ' ' ) || (i + 1 == s.size()))) {
reverse(s, word_begin, i);
word_begin = -1;
}
i++;
}
reverse(s, 0, s.size() - 1);
}
int main()
{
string s = "i like this program very much" ;
reverseWords(s);
cout << s << endl;
;
return 0;
}
|
C
#include <stdio.h>
void reverse( char * begin, char * end)
{
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
void reverseWords( char * s)
{
char * word_begin = NULL;
char * temp = s;
while (*temp) {
if ((word_begin == NULL) && (*temp != ' ' )) {
word_begin = temp;
}
if (word_begin
&& ((*(temp + 1) == ' ' )
|| (*(temp + 1) == '\0' ))) {
reverse(word_begin, temp);
word_begin = NULL;
}
temp++;
}
reverse(s, temp - 1);
}
int main()
{
char s[] = "i like this program very much" ;
char * temp = s;
reverseWords(s);
printf ( "%s" , s);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void reverse( char [] str, int start, int end)
{
char temp;
while (start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static char [] reverseWords( char [] s)
{
int word_begin = - 1 ;
int i = 0 ;
while (i < s.length) {
if ((word_begin == - 1 ) && (s[i] != ' ' )) {
word_begin = i;
}
if (word_begin != - 1
&& ((i + 1 == s.length)
|| (s[i + 1 ] == ' ' ))) {
reverse(s, word_begin, i);
word_begin = - 1 ;
}
i++;
}
reverse(s, 0 , (s.length - 1 ));
return s;
}
public static void main(String[] args)
{
String s = "i like this program very much" ;
char [] p = reverseWords(s.toCharArray());
System.out.println(p);
}
}
|
Python3
def reverse( str , start, end):
temp = ''
str1 = ""
while (start < = end):
temp = str [start]
str [start] = str [end]
str [end] = temp
start + = 1
end - = 1
return str1.join( str )
def reverseWords(s):
word_begin = - 1
i = 0
while (i < len (s)):
if ((word_begin = = - 1 ) and (s[i] ! = ' ' )):
word_begin = i
if (word_begin ! = - 1 and ((i + 1 = = len (s)) or (s[i + 1 ] = = ' ' ))):
s = reverse( list (s), word_begin, i)
word_begin = - 1
i + = 1
s = reverse( list (s), 0 , ( len (s) - 1 ))
return s
s = "i like this program very much"
p = reverseWords( list (s))
print (p)
|
C#
using System;
class GFG
{
static void reverse( char [] str, int start, int end)
{
char temp;
while (start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static char [] reverseWords( char [] s)
{
int word_begin = -1;
int i = 0;
while (i < s.Length) {
if ((word_begin == -1) && (s[i] != ' ' )) {
word_begin = i;
}
if (word_begin != -1
&& ((i + 1 == s.Length)
|| (s[i + 1] == ' ' ))) {
reverse(s, word_begin, i);
word_begin = -1;
}
i++;
}
reverse(s, 0, (s.Length - 1));
return s;
}
static void Main( string [] args)
{
String s = "i like this program very much" ;
char [] p = reverseWords(s.ToCharArray());
Console.WriteLine(p);
}
}
|
Javascript
function reverse(s, begin, end) {
while (begin < end) {
let charArray = [...s];
let temp = charArray[begin];
charArray[begin] = charArray[end];
charArray[end] = temp;
begin++;
end--;
s = charArray.join( "" );
}
return s;
}
function reverseWords(s) {
let word_begin = -1;
let i = 0;
while (i < s.length) {
if ((word_begin == -1) && (s[i] != ' ' )) {
word_begin = i;
}
if (word_begin != -1
&& ((s[i + 1] == ' ' ) || (i + 1 == s.length))) {
s = reverse(s, word_begin, i);
word_begin = -1;
}
i++;
}
s = reverse(s, 0, s.length - 1);
return s;
}
let s = "i like this program very much" ;
s = reverseWords(s);
console.log(s);
|
Output
much very program this like i
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach: To solve the problem follow the below idea:
We can do the above task by splitting and saving the string in a reverse manner.
Follow the below steps to solve the problem:
- Store the string in the form of words
- Run a for loop in reverse order to print the words accordingly
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s[] = { "i" , "like" , "this" ,
"program" , "very" , "much" };
string ans = "" ;
for ( int i = 5; i >= 0; i--) {
ans += s[i] + " " ;
}
cout << (ans.substr(0, ans.length() - 1)) << endl;
return 0;
}
|
Java
public class ReverseWords {
public static void main(String[] args)
{
String s[]
= "i like this program very much" .split( " " );
String ans = "" ;
for ( int i = s.length - 1 ; i >= 0 ; i--) {
ans += s[i] + " " ;
}
System.out.println(
ans.substring( 0 , ans.length() - 1 ));
}
}
|
Python3
s = "i like this program very much"
words = s.split( ' ' )
string = []
for word in words:
string.insert( 0 , word)
print ( " " .join(string))
|
C#
using System;
public class ReverseWords {
public static void Main()
{
string [] s
= "i like this program very much" .Split( ' ' );
string ans = "" ;
for ( int i = s.Length - 1; i >= 0; i--) {
ans += s[i] + " " ;
}
Console.Write(ans.Substring(0, ans.Length - 1));
}
}
|
Javascript
<script>
var s= [ "i" , "like" , "this" , "program" , "very" , "much" ];
var ans = "" ;
for ( var i = 5; i >= 0; i--)
{
ans += s[i] + " " ;
}
document.write(ans.slice(0,ans.length-1));
</script>
|
Output
much very program this like i
Time Complexity: O(N)
Auxiliary Space: O(N)
Reverse words in a given string using the swap operation:
The above task can also be accomplished by splitting the words separately and directly swapping the string starting from the middle.
Follow the below steps to solve the problem:
- Store the string in the form of words
- Swap the words with each other starting from the middle
- Print the string
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string RevString(string s[], int l)
{
if (l % 2 == 0) {
int j = l / 2;
while (j <= l - 1) {
string temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
else {
int j = (l / 2) + 1;
while (j <= l - 1) {
string temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
string S = s[0];
for ( int i = 1; i < 6; i++) {
S = S + " " + s[i];
}
return S;
}
int main()
{
string s = "i like this program very much" ;
string words[]
= { "i" , "like" , "this" , "program" , "very" , "much" };
cout << RevString(words, 6) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static String[] RevString(String[] s, int l)
{
if (l % 2 == 0 ) {
int j = l / 2 ;
while (j <= l - 1 ) {
String temp;
temp = s[l - j - 1 ];
s[l - j - 1 ] = s[j];
s[j] = temp;
j += 1 ;
}
}
else {
int j = (l / 2 ) + 1 ;
while (j <= l - 1 ) {
String temp;
temp = s[l - j - 1 ];
s[l - j - 1 ] = s[j];
s[j] = temp;
j += 1 ;
}
}
return s;
}
public static void main(String[] args)
{
String s = "i like this program very much" ;
String[] words = s.split( "\\s" );
words = RevString(words, words.length);
s = String.join( " " , words);
System.out.println(s);
}
}
|
Python3
def RevString(s, l):
if l % 2 = = 0 :
j = int (l / 2 )
while (j < = l - 1 ):
s[j], s[l - j - 1 ] = s[l - j - 1 ], s[j]
j + = 1
else :
j = int (l / 2 + 1 )
while (j < = l - 1 ):
s[j], s[l - 1 - j] = s[l - j - 1 ], s[j]
j + = 1
return s
s = 'i like this program very much '
string = s.split( ' ' )
string = RevString(string, len (string))
print ( " " .join(string))
|
C#
using System;
class GFG {
static string RevString( string [] s, int l)
{
if (l % 2 == 0) {
int j = l / 2;
while (j <= l - 1) {
string temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
else {
int j = (l / 2) + 1;
while (j <= l - 1) {
string temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
string S = s[0];
for ( int i = 1; i < 6; i++) {
S = S + " " + s[i];
}
return S;
}
public static void Main()
{
string [] words
= { "i" , "like" , "this" , "program" , "very" , "much" };
string a = RevString(words, words.Length);
Console.WriteLine(a);
}
}
|
Javascript
<script>
function RevString(s, l)
{
if (l % 2 == 0)
{
let j = parseInt(l / 2, 10);
while (j <= l - 1)
{
let temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
else
{
let j = parseInt((l / 2), 10) + 1;
while (j <= l - 1)
{
let temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
let S = s[0];
for (let i = 1; i < 9; i++)
{
S = S + " " + s[i];
}
return S;
}
let s = "i like this program very much" ;
let words = [ "i" , "like" , "this" , "program" , "very much" ];
document.write(RevString(words, 9));
</script>
|
Output
much very program this like i
Time complexity: O(N)
Auxiliary Space: O(N)
Reverse words in a given string using constant space:
Follow the below steps to solve the problem:
- Go through the string and mirror each word in the string,
- Then, in the end, mirror the whole string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string reverse_words(string s)
{
int left = 0, i = 0, n = s.size();
while (s[i] == ' ' )
i++;
left = i;
while (i < n) {
if (i + 1 == n || s[i] == ' ' ) {
int j = i - 1;
if (i + 1 == n)
j++;
while (left < j)
swap(s[left++], s[j--]);
left = i + 1;
}
if (i > left && s[left] == ' ' )
left = i;
i++;
}
reverse(s.begin(), s.end());
return s;
}
int main()
{
string str = "i like this program very much" ;
str = reverse_words(str);
cout << str;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static String swap(String str, int i, int j)
{
char ch[] = str.toCharArray();
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return new String(ch);
}
public static String reverse_words(String s)
{
int left = 0 , i = 0 , n = s.length();
while (s.charAt(i) == ' ' )
i++;
left = i;
while (i < n) {
if (i + 1 == n || s.charAt(i) == ' ' ) {
int j = i - 1 ;
if (i + 1 == n)
j++;
while (left < j)
s = swap(s, left++, j--);
left = i + 1 ;
}
if (i > left && s.charAt(left) == ' ' )
left = i;
i++;
}
s = new StringBuilder(s).reverse().toString();
return s;
}
public static void main(String[] args)
{
String str
= "i like this program very much" ;
str = reverse_words(str);
System.out.println(str);
}
}
|
Python3
def reverse_words(s):
left = 0
i = 0
s = list (s)
n = len (s)
while (s[i] = = ' ' ):
i = i + 1
left = i
while (i < n):
if (i + 1 = = n or s[i] = = ' ' ):
j = i - 1
if i + 1 = = n:
j = j + 1
while left < j:
s[left], s[j] = s[j], s[left]
left = left + 1
j = j - 1
left = i + 1
if (i > left and s[left] = = ' ' ):
left = i
i = i + 1
s = ''.join(s)
s = s[:: - 1 ]
return s
s1 = "i like this program very much"
s1 = reverse_words(s1)
print (s1)
|
C#
using System;
class GFG {
public static string swap( string str, int i, int j)
{
char [] ch = str.ToCharArray();
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return new String(ch);
}
public static string reverse_words( string s)
{
int left = 0, i = 0, n = s.Length;
while (s[i] == ' ' )
i++;
left = i;
while (i < n) {
if (i + 1 == n || s[i] == ' ' ) {
int j = i - 1;
if (i + 1 == n)
j++;
while (left < j)
s = swap(s, left++, j--);
left = i + 1;
}
if (i > left && s[left] == ' ' )
left = i;
i++;
}
char [] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string (charArray);
}
public static void Main( string [] args)
{
string str = "i like this program very much" ;
str = reverse_words(str);
Console.WriteLine(str);
}
}
|
Javascript
function swap(s,a,b)
{
let charArray = [...s];
let temp = s[a];
charArray[a] = s[b];
charArray[b] = temp;
return charArray.join( "" );
}
function reverse(str) {
let charArray = [...str];
let ans = "" ;
for (let i=charArray.length-1;i>=0;i--)
{
ans+=charArray[i];
}
return ans;
}
function reverse_words(s)
{
let left = 0, i = 0, n = s.length;
while (s[i] == ' ' )
i++;
left = i;
while (i < n) {
if (i + 1 == n || s[i] == ' ' ) {
let j = i - 1;
if (i + 1 == n)
j++;
while (left < j)
{
s = swap(s,left++, j--);
}
left = i + 1;
}
if (i > left && s[left] == ' ' )
left = i;
i++;
}
s = reverse(s);
return s;
}
let str = "i like this program very much" ;
str = reverse_words(str);
console.log(str);
|
Output
much very program this like i
Time complexity: O(N)
Auxiliary Space: O(1)
Reverse words in a given string using constant space: using the slicing method and join functions:
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int main() {
string text = "i like this program very much" ;
vector<string> str;
istringstream iss(text);
for (string s; iss >> s;) {
str.push_back(s);
}
reverse(str.begin(), str.end());
cout << str[0];
for ( int i = 1; i < str.size(); i++) {
cout << " " << str[i];
}
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
String text
= "i like this program very much" ;
String str[] = text.split( " " );
Collections.reverse(Arrays.asList(str));
System.out.println(String.join( " " , str));
}
}
|
Python3
string = "i like this program very much"
s = string.split()[:: - 1 ]
print ( " " .join(s))
|
C#
using System;
using System.Linq;
public class GFG {
static public void Main()
{
string text
= "i like this program very much" ;
Console.WriteLine(
string .Join( " " , text.Split( ' ' ).Reverse()));
}
}
|
Javascript
let text= "i like this program very much" ;
let str = text.split( " " );
str.reverse();
str = str.join( " " );
console.log(str);
|
PHP
<?php
$string = "i like this program very much" ;
$array = explode ( " " , $string );
$rarray = array_reverse ( $array );
echo $newstring = implode( " " , $rarray );
?>
|
Output
much very program this like i
Time complexity: O(N2)
Auxiliary Space: O(N)
Approach: Without splitting the string
By this approach, we can even remove extra trailing spaces and in between the words also.
Basically, this algorithm involves 3 steps.
If you find white space, there can be two possibilities.
It might be end of a word or else extra trailing space in between the words.
if it is not a white space, add the character to temporary word as shown in the below code.
C++
#include <iostream>
#include <string>
using namespace std;
string reverseString(string s)
{
string ans = "" ;
string temp = "" ;
for ( int i = 0; i < s.length(); i++)
{
char ch = s[i];
if (ch == ' ' )
{
if (temp != "" )
{
ans = temp + " " + ans;
}
temp = "" ;
}
else
{
temp += ch;
}
}
if (temp != "" )
{
ans = temp + " " + ans;
}
if (ans.length() > 0 && ans[ans.length() - 1] == ' ' )
{
ans = ans.substr(0, ans.length() - 1);
}
return ans;
}
int main()
{
string s1 = " Welcome to Geeks For Geeks " ;
cout << "Before reversing length of string : "
<< s1.length() << endl;
string ans1 = reverseString(s1);
cout << "After reversing length of string : "
<< ans1.length() << endl;
cout << "\"" << ans1 << "\"" << endl;
string s2 = " I Love C++ Programming " ;
cout << "Before reversing length of string : "
<< s2.length() << endl;
string ans2 = reverseString(s2);
cout << "After reversing length of string : "
<< ans2.length() << endl;
cout << "\"" << ans2 << "\"" << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static String reverseString(String s)
{
StringBuilder ans= new StringBuilder();
String temp = "" ;
for ( int i= 0 ;i<s.length();i++)
{
char ch = s.charAt(i);
if (ch== ' ' )
{
if (!temp.equals( "" ))
{
ans.insert( 0 ,temp+ " " );
}
temp = "" ;
}
else
temp += ch;
}
return ans.toString().substring( 0 ,ans.length()- 1 );
}
public static void main(String[] args) {
String s1= " Welcome to Geeks For Geeks " ;
System.out.println( "Before reversing length of string : " +s1.length());
String ans1=reverseString(s1);
System.out.println( "After reversing length of string : " +ans1.length());
System.out.println( "\"" +ans1+ "\"\n" );
String s2= " I Love Java Programming " ;
System.out.println( "Before reversing length of string : " +s2.length());
String ans2=reverseString(s2);
System.out.println( "After reversing length of string : " +ans2.length());
System.out.println( "\"" +ans2+ "\"" );
}
}
|
Python3
def reverseString(s):
ans = ""
temp = ""
for ch in s:
if ch = = ' ' :
if temp:
ans = temp + " " + ans
temp = ""
else :
temp + = ch
if temp:
ans = temp + " " + ans
if ans and ans[ - 1 ] = = ' ' :
ans = ans[: - 1 ]
return ans
if __name__ = = "__main__" :
s1 = " Welcome to Geeks For Geeks "
print ( "Before reversing length of string:" , len (s1))
ans1 = reverseString(s1)
print ( "After reversing length of string:" , len (ans1))
print ( "\"" + ans1 + "\"" )
s2 = " I Love Python Programming "
print ( "Before reversing length of string:" , len (s2))
ans2 = reverseString(s2)
print ( "After reversing length of string:" , len (ans2))
print ( "\"" + ans2 + "\"" )
|
C#
using System;
class GFG {
public static string ReverseString( string s)
{
var ans = new System.Text.StringBuilder();
var temp = "" ;
for ( var i=0;i<s.Length;i++)
{
var ch = s[i];
if (ch== ' ' )
{
if (!temp.Equals( "" ))
{
ans.Insert(0,temp+ " " );
}
temp = "" ;
}
else
temp += ch;
}
return ans.ToString().Substring(0,ans.Length-1);
}
public static void Main( string [] args) {
var s1= " Welcome to Geeks For Geeks " ;
Console.WriteLine( "Before reversing length of string : " +s1.Length);
var ans1=ReverseString(s1);
Console.WriteLine( "After reversing length of string : " +ans1.Length);
Console.WriteLine( "\"" +ans1+ "\"\n" );
var s2= " I Love Java Programming " ;
Console.WriteLine( "Before reversing length of string : " +s2.Length);
var ans2=ReverseString(s2);
Console.WriteLine( "After reversing length of string : " +ans2.Length);
Console.WriteLine( "\"" +ans2+ "\"" );
}
}
|
Javascript
function reverseString(s) {
let ans = "" ;
let temp = "" ;
for (let i = 0; i < s.length; i++) {
let ch = s[i];
if (ch === ' ' ) {
if (temp !== "" ) {
ans = temp + " " + ans;
}
temp = "" ;
} else {
temp += ch;
}
}
if (temp !== "" ) {
ans = temp + " " + ans;
}
if (ans.length > 0 && ans[ans.length - 1] === ' ') {
ans = ans.substring(0, ans.length - 1);
}
return ans;
}
let s1 = " Welcome to Geeks For Geeks " ;
console.log( "Before reversing length of string : " + s1.length);
let ans1 = reverseString(s1);
console.log( "After reversing length of string : " + ans1.length);
console.log( "\"" + ans1 + "\"" );
let s2 = " I Love JavaScript Programming " ;
console.log( "Before reversing length of string : " + s2.length);
let ans2 = reverseString(s2);
console.log( "After reversing length of string : " + ans2.length);
console.log( "\"" + ans2 + "\"" );
|
Output
Before reversing length of string : 28
After reversing length of string : 26
"Geeks For Geeks to Welcome"
Before reversing length of string : 31
After reversing length of string : 23
"Programming Java Love I"
Time Complexity: O(N) where N is length of string
Auxiliary Space: O(1)
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...