美文网首页
151. Reverse Words in a String

151. Reverse Words in a String

作者: jluemmmm | 来源:发表于2021-02-11 11:23 被阅读0次

    字符串里的单词反转

    转为数组

    • 时间复杂度O(N),空间复杂度O(N)
    • Runtime: 72 ms, faster than 96.97%
    • Memory Usage: 40.5 MB, less than 35.39%
    /**
     * @param {string} s
     * @return {string}
     */
    var reverseWords = function(s) {
        return s.split(' ').filter(i => i.length).reverse().join(' ')
    };
    

    正则

    • Runtime: 72 ms, faster than 96.97%
    • Memory Usage: 40.7 MB, less than 24.93%
    /**
     * @param {string} s
     * @return {string}
     */
    var reverseWords = function(s) {
        return s.match(/[\S]+/g).reverse().join(' ')
         // return s.match(/[\S]+/ig).reverse().join(" ")
    };
    

    手动实现

    • Runtime: 88 ms, faster than 36.56%
    • Memory Usage: 41 MB, less than 13.20%
    /**
     * @param {string} s
     * @return {string}
     */
    var reverseWords = function(s) {
        let match = s.match(/[\S]+/g)
        let res = ''
        console.log(match)
        while(match.length > 0) {
            if(!res) res = match.shift() + res
            else res = (match.shift() + ' ') + res
            // console.log(res)
        }
        return res
    };
    

    相关文章

      网友评论

          本文标题:151. Reverse Words in a String

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