企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. Example 1: ``` Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc" Note: In the string, each word is separated by single space and there will not be any extra space in the string. ``` ``` /** * @param {string} s * @return {string} */ //方法1 var reverseWords = function(s) { var arr = s.split(' '); var Arr = []; for(let i = 0; i<arr.length; i++){ Arr.push(arr[i].split('').reverse().join('')); } var str = Arr.join(' '); return str; }; //方法2 var reverseWords = function(s) { let arr = s.split(' '); let result = arr.map(item =>{ return item.split('').reverse().join('') } ) return result.join(' '); }; //方法3 var reverseWords = function(s) { return s.split(' ').map(item =>{ return item.split('').reverse().join('') } ).join(' '); }; //方法4 var reverseWords = function(s) { return s.split(/\s/g/).map(item =>{ return item.split('').reverse().join('') } ).join(' '); }; //方法4 var reverseWords = function(s) { return s.match(/[\w']+/g/).map(item =>{ return item.split('').reverse().join('') } ).join(' '); }; ``` ``` var reverseWords = function(s) { return s.split("").reverse().join("").split(" ").reverse(" ").join(" "); }; ``` ![](https://img.kancloud.cn/24/cf/24cf34dc3f226b8319c3500a57896e65_924x341.png)