在字母列表中查找丢失的字母 [英] Find missing letter in list of alphabets

查看:56
本文介绍了在字母列表中查找丢失的字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决以下问题:

I am trying to solve the following issue:

在传递的字母范围内找到丢失的字母并返回.如果所有字母都在该范围内,则返回undefined.

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

我将以字符串形式获得的输入是:

the inputs that I will get as strings are:

  • abce(应该返回d)
  • bcd(应该返回未定义)
  • abcdefghjklmno(应该返回i)
  • yz(应该返回未定义)

我的代码当前如下所示:

my code currently looks like this:

  function fearNotLetter(str) {
  //create alphabet string
  //find starting letter in alphabet str, using str
  //compare letters sequentially
  //if the sequence doesn't match at one point then return letter
  //if all letters in str appear then return undefined

  var alphabet = ("abcdefgheijklmnopqrstuvwxyz");
  var i = 0;
  var j = 0;
  while (i<alphabet.length && j<str.length) {
    i++;
    if (alphabet.charCodeAt(i) === str.charCodeAt(j)) {
      i++;
      j++;      
    }
    else if (alphabet.charCodeAt(i) !== str.charCodeAt(j)) {
      i++;
      j++;
      if (alphabet.charCodeAt(i) === str.charCodeAt(j-1)) {
        return alphabet.charCodeAt(i-1);  
      }
    }
  }
}

fearNotLetter('abce');

感谢您的一如既往!

推荐答案

我会这样:

function fearNotLetter(str) {
    var i, j = 0, m = 122;
    if (str) {
        i = str.charCodeAt(0);
        while (i <= m && j < str.length) {
            if (String.fromCharCode(i) !== str.charAt(j)) {
                return String.fromCharCode(i);
            }
            i++; j++;
        }
    }
    return undefined;
}

console.log(fearNotLetter('abce'));        // "d"
console.log(fearNotLetter('bcd'));         // undefined
console.log(fearNotLetter('bcdefh'));      // "g"
console.log(fearNotLetter(''));            // undefined
console.log(fearNotLetter('abcde'));       // undefined
console.log(fearNotLetter('abcdefghjkl')); // "i"

i 的范围可以从97到122,此间隔对应于下方的ASCII码大小写字母.

i can go from 97 to 122, this interval corresponds to the ASCII codes of the lower case alphabet.

如果不希望区分大小写,只需在函数开始处执行 str = str.toLowerCase().

If you want it not to be case sensitive, just do str = str.toLowerCase() at the beginning of the function.

这篇关于在字母列表中查找丢失的字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆