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.
LeetCode Problem - 151: Link | Click Here
class Solution {
public String reverseWords(String s) {
// Create a StringBuilder to build the reversed string
StringBuilder sb = new StringBuilder();
// Remove extra spaces between words by replacing multiple spaces with a single space
String removeExtraSpace = s.replaceAll("\\s+", " ");
// Split the string into an array of words using space as the delimiter
String[] resultString = removeExtraSpace.split(" ");
// Iterate through the array of words in reverse order and append each word to the StringBuilder
for (int j = resultString.length - 1; j >= 0; j--) {
sb.append(resultString[j]).append(" ");
}
// Convert the StringBuilder to a string and trim any leading or trailing spaces
String reversedString = sb.toString().trim();
// Return the final reversed string
return reversedString;
}
}