0

我正在尝试自学编程并从 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 分钟。所以我的问题是我是否把事情复杂化了?导致我编写比需要更长的脚本?我已经阅读了一些关于正则表达式之类的内容,以及它们如何真正缩短脚本长度以及编写它们所需的时间,或者可能是另一种比我必须制作的所有循环更有用的技术?

4

1 回答 1

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/

被评论了。希望能帮助到你 :)

于 2013-10-30T19:57:09.020 回答