字符串里的单词反转
转为数组
- 时间复杂度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
};
网友评论