151. Reverse Words in a String - Medium
Given an input string s, reverse the order of the words. Return a string of the words in reverse order concatenated by a single space.
Example:
Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces in the reversed string.
Constraints:
1 <= s.length <= 10**4
s contains English letters
There is at least one word in s.
Solution:
var reverseWords = function(s) {
return s.split(' ').reverse().filter(x => x !== '').join(' ');
}
Thoughts:
Happy with the one-line solution. I would struggle to solve this if I couldn't use the built-in js methods (reverse especially). The solution beats 49% of solutions, which is better than I thought. I did need to debug what s looked like after I split on all the spaces and then that's when I clocked so we could filter out the empty array values. I'd give my understanding an 8/10. Happy that it's a medium.
Comments
Post a Comment