2021年5月13日,雨天,穿短袖好冷,真是个学习的好日子。
今天是开始教练开始带着学leetcode的第七天。
今天学习替换空格,难度简单,请听题:
答题时间:
1: 直接使用自带的方法来操作
function replaceSpace(str) {if (str.length > 10000 || str.length === 0) {return ''}let ss = str.split(' ')for (let index = 0; index < ss.length; index++) {if (ss[index] === '') {ss[index] = "%20"}}return ss.join('')}
2:双指针的操作:
// 输入:s = "We are happy."// 输出:"We%20are%20happy."function replaceSpace(str) {if (!str || !str.length) {return ''}// 1: 算出空格和非空格的值。let emptyNum = 0;let chNum = 0;for (let index = 0; index < str.length; index++) {if (str[index] == ' ') {emptyNum++;} else {chNum++;}}let chS = new Array(emptyNum * 2 + chNum);// 2: 准备两个指针开始遍历let i = 0; // 原始let j = 0; // 新for (let i = 0, j = 0; j < str.length; j++) {if (str[i] == ' ') {chS[j++] = '%'chS[j++] = '2'chS[j++] = '0'} else {chS[i++] = str[j]}}return chS.join('')}
