151. Reverse Words in a String
#string #array
Given an input string s
, 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.
Intuition
split the string on space and add words in the final string from end
Approach
trim the string to remove any trailing or leading whitespace
split the string using
string.split(" ")
iterate over the words from the end
trim the word before appending to final result to ensure we dont add any whitespace
Complexity
Space Complexity
Time Complexity
we store the splitted string in an array
we iterate over the words in the string once
Code
Last updated