4 - 151. Reverse Words in a Stri
2021-02-12 本文已影响0人
bestCindy
https://leetcode.com/problems/reverse-words-in-a-string/
var reverseWords = function(s) {
let arr = s.split(' ').filter(val => val != '');
let newStr = '';
for (let i = arr.length - 1; i >=0; i--) {
newStr += ' ' + arr[i];
}
return newStr.trim();
};
the better solution use different approach
var reverseWords = function(s) {
let ret = [];
let word = '';
for (let i = 0; i < s.length; i++) {
if (s[i] === ' ') {
word.length > 0 && ret.unshift(word);
word = '';
} else {
word += s[i];
}
}
word.length > 0 && ret.unshift(word);
return ret.join(' ')
};