Problem
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.
We want to return a string of the words in reverse order concatenated by a single space.
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.
Discussion
- Check if the input string
s
is null or empty. If it is, return an empty string. - Trim the input string to remove leading and trailing white space.
- Create a
StringBuilder
object namedreversedString
to store the reversed string. - Split the trimmed string
s
into an array of words using thesplit(" ")
method, which splits the string based on spaces. - Iterate over the
strArray
from the last element to the first (strArray.length - 1
to 0). - Inside the loop, check if the current word
strArray[i]
is not an empty string. - If the word is not empty, append it to the
reversedString
using theappend()
method. - If the current word is not the first word in the reversed order (i.e.,
i != 0
), append a space after the word. - After the loop ends, convert the
reversedString
to a regular string using thetoString()
method. - Return the reversed string as the result of the method.
Time Complexity
- Splitting the string into an array of words using
split(" ")
takes O(n) time, where n is the length of the input string. - The for loop iterates over the array of words, which takes O(m) time, where m is the number of words in the array.
- Within the loop, appending words to the
reversedString
takes O(1) time. - Overall, the time complexity of the algorithm is O(n + m), where n is the length of the input string and m is the number of words.
Space Complexity
- The space complexity of the algorithm is O(n + m), where n is the length of the input string and m is the number of words.
- The trimmed string
s
and the arraystrArray
both require O(n) space. - The
reversedString
StringBuilder requires additional space to store the reversed string, which can be up to O(n) in the worst case if all words are present. - Therefore, the total space complexity is O(n + m).
Java Solution
public String reverseWords(String s) {
if(s == null || s.length() == 0) return "";
s = s.trim();
StringBuilder reversedString = new StringBuilder();
String[] strArray = s.split(" ");
for( int i = strArray.length -1; i >= 0; i--){
if(!strArray[i].equals("")){
reversedString.append(strArray[i]);
if(i != 0) reversedString.append(" ");
}
}
return reversedString.toString();
}
Python Solution
def reverseWords(self, s):
if s is None or len(s) == 0:
return ""
s = s.strip()
reversed_string = []
str_list = s.split(" ")
for i in range(len(str_list) - 1, -1, -1):
if str_list[i] != "":
reversed_string.append(str_list[i])
return " ".join(reversed_string)
Check out my other article or Algorithm – Roman To Integer here
Our Facebook page is here. You can also find our youtube channel here.