美文网首页
4 - 151. Reverse Words in a Stri

4 - 151. Reverse Words in a Stri

作者: bestCindy | 来源:发表于2021-02-12 23:45 被阅读0次

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(' ')
};

相关文章

网友评论

      本文标题:4 - 151. Reverse Words in a Stri

      本文链接:https://www.haomeiwen.com/subject/ujajxltx.html