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.
Note that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
Example 1:
Input: s = "the sky is blue" Output: "blue is sky the"
Example 2:
Input: s = " hello world " Output: "world hello" Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = "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.
Constraints:
1 <= s.length <= 104
s
contains English letters (upper-case and lower-case), digits, and spaces ' '
.s
.
class Solution {
public:
string reverseWords(string s) {
int i=s.length()-1;
string ans="";
string helper="";
for(int j=i; j>=0; j--)
{
if(s[j]==' ')
{
if(helper.size()!=0)
{
reverse(helper.begin(),helper.end());
ans+=helper;
ans+=" ";
helper="";
}
}
else
{
helper+=s[j];
}
}
if(helper.size()!=0)
{
reverse(helper.begin(),helper.end());
ans+=helper;
}
else if(ans.size()!=0)ans.pop_back();
return ans;
}
};
class Solution {
public String reverseWords(String s) {
String[] arr = s.split("\\s+"); // split on the basis of spaces
StringBuilder sb = new StringBuilder("");
for(int i=arr.length-1;i>=0;i--){
sb.append(arr[i] + " ");
}
// trim function --> remove trailing and leading spaces
String ans = sb.toString();
ans = ans.trim();
return ans ;
}
}
In this program, we have to reverse the order of words while keeping the word’s direction the same. Only the words will be interchanged.
For this purpose, we will:
1. We initialize an integer variable ‘i’ to the length of the input string minus one (the index of the last character in the string) and we also initialize two empty strings: ‘ans’ and ‘helper’.
2. If we encounter space anywhere in between then check
3. After the loop, it checks if ‘helper’ is not empty . If ‘helper’ is not empty , it means the last word has been collected , and it will be added to the ‘ans’ .
• The code reverses the the order of characters in ‘helper’ and directs it to ‘ans’ , and ensures that there is no extra space at the end.
4. Finally, the string with reversed words is stored in ‘ans’, and it is returned as a result.
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India