我怎么能缩短这个?

时间:2013-10-30 19:21:15

标签: javascript for-loop while-loop

我正在尝试自学编程并开始使用javascript。要了解更多信息,我一直在完成实践挑战,其中一个挑战是编写一个脚本,用于确定字符串中包含最多重复字母的单词的第一个案例。我用这个代码完成了它:

string = "Hey i believe";
string = string.split(" ");
stringarray = [];
longestlength = 0; 

for (i = 0; i < string.length; i++) {
    stringarray.push(0);
}

for (i = 0; i < string.length; i++) {
    if (string[i].length > longestlength) {
        longestlength = string[i].length;
        longestword = string[i];
    }
}

for (x = 0; x < string.length; x++) {
    y = 0;
    z = 0;
    while (z < string[x].length) {
        if (string[x].substr(z,1) == string[x].substr(y,1) && z !== y) {
            stringarray[x] += 1;
            y = string[x].length -1;
        }
        y++;
        if (y == string[x].length) {
            z++;
            y = z;
        }
    }
}

if (Math.max.apply(null,stringarray) === 0) {
    mostrptltword = -1;
}
else {
    mostrptltword = string[stringarray.indexOf(Math.max.apply(null,stringarray))];
}

console.log(mostrptltword);

但为了获得所有可能的挑战,必须在不到10分钟的时间内完成,这需要我25分钟。所以我的问题是我过于复杂化了吗?让我写一个比需要更长的脚本?我已经阅读了一些关于正则表达式的内容以及它们如何真正缩短脚本长度以及编写它们所需的时间,或者可能是另一种比我必须做的所有循环更有用的技术?

1 个答案:

答案 0 :(得分:1)

var words = "Heyyyyy I believe".split(' '); // split the words into an array


var values = [],   // total of times that a letter appears
    k = 0,         // 'global' counter. I'm using this to iterate over the values array
    heigher = 0,   // holds de heigher occurrence of a letter 
    letter = "";   // the letter that most appears in that word
    word = "";     // the word


// iterate over all the words
for(var i = 0; i < words.length; i++) {  

    // iterate over each letter in each word
    for(var j = 0; j < words[i].length; j++) {

        // holds the occurrence time
        // RegEx: get the word in the position 'i' and check how many times the letter appears on the position [j] appears
        values[k] = words[i].match(new RegExp(words[i][j],'g')).length;

        // check if the next letter appears more times than the previous one
        if(values[k] > heigher) {
            // hold the values of interest
            heigher = values[k];
            letter = words[i][j];
            word = words[i];
        }
        k++;
    } 
}

console.log("word: " + word + " letter: " + letter + " total: " + heigher);

jsfiddle:http://jsfiddle.net/felipemiosso/FyCHG/

评论。希望它有所帮助:)