communicate icon indicating copy to clipboard operation
communicate copied to clipboard

finish question 1,2,3,4,5,6,7

Open SimplyY opened this issue 9 years ago • 6 comments

SimplyY avatar Feb 11 '16 11:02 SimplyY

var int = Number.parseInt(str, 10);

这里可以直接用全局的parseInt(str, 10)方法,书写简单很多;也可以直接用Number(str)包裹实现。

abell123456 avatar Feb 16 '16 09:02 abell123456

var intAry = ary.map(function(item) {
    return Number(item);
});

这里可以直接写成:

var intAry = ary.map(Number);

abell123456 avatar Feb 16 '16 09:02 abell123456

path = path.replace(regexp, '$1$2');

能否写的正则按照下面要求直接实现呢?

path = path.replace(regexp, '$1');

参考写法:

/^([A-Z]+:)(\/[^\/]+)/

abell123456 avatar Feb 16 '16 09:02 abell123456

其他的都没问题 :)
第7题给出我自己写的参考答案,用了递归,你看下:

function getRes(str) {
    if (/^([a-cA-C])\1*$/g.test(str)) {
        return str;
    }
    var allRepAry = getAllRep(str),
        index, strLen, subLen;
    if (allRepAry) { //有重复
        var v = allRepAry[0];
        index = str.indexOf(v);
        strLen = str.length;
        subLen = v.length;
        var compStr;
        if (index === 0) { // 开头
            compStr = v + str.charAt(subLen);
        } else { // 结尾或中间
            compStr = str.charAt(index - 1) + v;
        }
        str = str.replace(compStr, removeRep(compStr, v));
        str = getRes(str);

    } else { //没有重复的
        var firTwoStr = str.substring(0, 2);
        str = str.replace(firTwoStr, dif(firTwoStr));
        str = getRes(str);
    }
    return str;
}

function removeRep(str, rep) {
    var isOdd = rep.length % 2 === 0,
        index = str.indexOf(rep),
        repLen = rep.length,
        oneS = rep.charAt(0),
        secS = index === 0 ? str.slice(repLen, repLen + 1) : str.slice(0, 1);

    if (isOdd) {
        return secS;
    } else {
        var sss = "abc",
            ind1 = sss.indexOf(oneS),
            ind2 = sss.indexOf(secS);
        return sss.charAt(3 - ind1 - ind2);
    }
}

function dif(str) {
    if (!/^[a-cA-C]{2}$/g.test(str)) {
        throw new Error("请输入长度为2且只包含a、b、c的字符串");
    }
    var s = "abc",
        s1 = str.charAt(0),
        s2 = str.charAt(1),
        ind1 = s.indexOf(s1),
        ind2 = s.indexOf(s2);
    return /^([A-Za-z])\1$/g.test(str) ? str : s.charAt(3 - ind1 - ind2);
}

function getAllRep(str) {
    return str.match(/([a-cA-C])\1+/g); // 要求至少有两个重复
}

function getManLen(str) {
    return getRes(str).length;
}
console.log(getManLen("bcab"));

abell123456 avatar Feb 16 '16 09:02 abell123456

您给出的代码是看得懂,但是算法思想没看懂,于是后来搜了一下,看到

每次消除时都能保证最短即可

这句话的时候恍然大悟,局部最优就可以达到整体最优 ,使用贪心算法就 ok 了(之前就是不知道如何才能找到最优解,尝试了几个,但是思路不对,贪心简直快加好)

于是我就上午花了两小时将算法思路整理好,再写成代码,最后测试,代码运行速度还行。

SimplyY avatar Feb 17 '16 04:02 SimplyY

第一期所有题目现在算是全部完成,从中受益匪浅,对Angular.js的依赖注入、正则匹配、 dom 事件、 promise、算法都有了进一步加深的理解,非常期待第二期,我准备把一二期的心得收获合在一起做个笔记,倒时候也可以把笔记 PR 到这里。

非常感谢。

SimplyY avatar Feb 17 '16 04:02 SimplyY