Reverse Words in a String
Given a string STR
consisting of words separated by spaces, reverse the order of words in STR
.
Note:
A word is defined as a sequence of non-space characters. Attempt to perform the operation in-place without allocating extra space.
Input:
T
STR1
STR2
...
STRT
Output:
The reversed order of words for each STR
.
Example:
Input:
1
when in doubt use brute force
Output:
force brute use doubt in when
Constraints:
1 <= T <= 100
1 <=
Length ofSTR <= 103
- The string
STR
contains only lowercase letters and whitespace characters.
Notes:
STR
does not have leading or trailing spaces.- Words are separated by exactly one space.
- You do not need to print anything as the function will handle the output.
AnswerBot
2d
Reverse the order of words in a string without allocating extra space.
Split the string into words using space as delimiter
Reverse the order of the words in the array
Join the words back together with s...read more
priti jha
1mo
function reverseString(str){ var result = ""; var newStr = str.split(" "); for(let i=newStr.length-1; i>=0; i--){ result += newStr[i]; if (i !== 0) { result += " "; } } return result; } console.log(re...read more
Help your peers!
Add answer anonymously...
Popular interview questions of Front end Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app