2021年5月13日,雨天,穿短袖好冷,真是个学习的好日子。
    今天是开始教练开始带着学leetcode的第七天。
    今天学习替换空格,难度简单,请听题:
    WechatIMG1396.png
    答题时间:

    1: 直接使用自带的方法来操作

    1. function replaceSpace(str) {
    2. if (str.length > 10000 || str.length === 0) {
    3. return ''
    4. }
    5. let ss = str.split(' ')
    6. for (let index = 0; index < ss.length; index++) {
    7. if (ss[index] === '') {
    8. ss[index] = "%20"
    9. }
    10. }
    11. return ss.join('')
    12. }

    2:双指针的操作:

    1. // 输入:s = "We are happy."
    2. // 输出:"We%20are%20happy."
    3. function replaceSpace(str) {
    4. if (!str || !str.length) {
    5. return ''
    6. }
    7. // 1: 算出空格和非空格的值。
    8. let emptyNum = 0;
    9. let chNum = 0;
    10. for (let index = 0; index < str.length; index++) {
    11. if (str[index] == ' ') {
    12. emptyNum++;
    13. } else {
    14. chNum++;
    15. }
    16. }
    17. let chS = new Array(emptyNum * 2 + chNum);
    18. // 2: 准备两个指针开始遍历
    19. let i = 0; // 原始
    20. let j = 0; // 新
    21. for (let i = 0, j = 0; j < str.length; j++) {
    22. if (str[i] == ' ') {
    23. chS[j++] = '%'
    24. chS[j++] = '2'
    25. chS[j++] = '0'
    26. } else {
    27. chS[i++] = str[j]
    28. }
    29. }
    30. return chS.join('')
    31. }