• 漂亮的代码5:数组与字符一样的操作


    看到这题:

    
    // 依次替换第一个参数中的字符串,用第二个参数。
    var str = "TRaduttore"
    
    str.tr( "auioe", "4-103" )  // -> "TR4d-tt0r3"
    str.tr( "aeiouR", ["A","E","I","O","U","r"] )  // -> "TrAdUttOrE"
    
    var hi = "Hello Happy CodeWarriors"
    
    hi.tr( ["ello","Happy","Wa","ior"],["ola","Felices","Gue","ero"]) // -> "Hola Felices CodeGuerreros"
    hi.tr( ["ll","pp","rr"], "LPR" )  // -> "HeLo HaPy CodeWaRiors"
    
    

    这是我解决的方案:

    String.prototype.tr1 = function(fromList, toList) {
        fromList = fromList || [];
        toList = toList || [];
    
        var pairs = {};
    
        var a = Array.isArray(fromList) ? fromList : fromList.split("");
        var b = Array.isArray(toList) ? toList : toList.split("");
    
        a.forEach((x, i) => pairs[x] = b[i]);
    
        return a.reduce((acc, cur) => acc.replace(new RegExp(cur, "g"), function(x) {
            return pairs[x] + "" || ""; // 这里如果 toList 中包括 0 的话就不行,所以加上一个空字符转成字符,在这里卡了很久。
        }), this);
    
    }
    
    

    看别人的解决方案:

    String.prototype.tr = function(from, to) {
        for (var s = this, i = 0; i < from.length; i++) {
            s = s.split(from[i]).join(to ? to[i] : '');
        }
    
        return s;
    }
    
    // 我自己改进一下
    String.prototype.tr = function(from, to) {
        return (Array.isArray(from) ? from : from.split("")).reduce((acc, cur, i) => acc.split(cur).join(to ? to[i] : ''), this);
    }
    
    

    自己写成了一堆屎,好好学习。

  • 相关阅读:
    Leet_Code_567_字符串排列
    LeetCode_424_替换后的最长字符串
    LeetCode_139_单词拆分
    为Linux 添加自定义命令
    javax.validation 自定义校验器
    MYBatis 动态SQL
    SPRING BOOT 15.1 TEST
    B-树和B+树的应用:数据搜索和数据库索引
    设计模式-代理
    数据结构与算法
  • 原文地址:https://www.cnblogs.com/htoooth/p/5546646.html
Copyright © 2020-2023  润新知