Find missing letter in list of alphabets

前端 未结 16 1553
逝去的感伤
逝去的感伤 2021-01-01 05:15

I am trying to solve the following issue:

Find the missing letter in the passed letter range and return it. If all letters are present in the range, return undefine

16条回答
  •  借酒劲吻你
    2021-01-01 05:20

    I think this is the simplest code to do this:

    function skippedLetter(str) {
        for (var i = 0; i < str.length - 1; i++) {
            if (str.charCodeAt(i + 1) - str.charCodeAt(i) != 1) {
                return String.fromCharCode(str.charCodeAt(i) + 1);
            }
        }
    }
    
    alert(skippedLetter('abce'));

    This version will reject illegal input, accept both upper and lower case, check that there is only 1 hole in the range, and that there is exactly 1 character missing.

    function skippedLetter(str) {
        if (!str.match(/^[a-zA-Z]+$/)) return;
        var letter = "", offset = str.charCodeAt(0);
        for (var i = 1; i < str.length; i++) {
            var diff = str.charCodeAt(i) - i - offset;
            if (diff == 1) letter += String.fromCharCode(i + offset++)
            else if (diff) return;
        }
        if (letter.length == 1) return letter;
    }
    
    alert(skippedLetter('123567'));		// illegal characters
    alert(skippedLetter(''));		// empty string
    alert(skippedLetter('a'));		// too short
    alert(skippedLetter('bc'));		// nothing missing
    alert(skippedLetter('df'));		// skipped letter = e
    alert(skippedLetter('GHIKLM'));		// skipped letter = J
    alert(skippedLetter('nOpRsT'));		// cases mixed
    alert(skippedLetter('nopxyz'));		// too many characters missing
    alert(skippedLetter('abcefgijk'));	// character missing more than once
    alert(skippedLetter('abcefgfe'));	// out of order

提交回复
热议问题