gpt4 book ai didi

javascript - 在字母列表中查找丢失的字母

转载 作者:搜寻专家 更新时间:2023-11-01 04:50:10 24 4
gpt4 key购买 nike

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

在传递的字母范围内找到丢失的字母并返回。如果范围内存在所有字母,则返回未定义。

我将作为字符串获得的输入是:

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

我的代码目前看起来像这样:

  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 codes of the lower case alphabet .

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

关于javascript - 在字母列表中查找丢失的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com