如何找到数组中缺少的下一个字符? [英] How to find the missing next character in the array?

查看:85
本文介绍了如何找到数组中缺少的下一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符数组:

I have an array of characters like this:

['a','b','c','d','f']
['O','Q','R','S']

如果看到这一点,则每个数组中都缺少一个字母。第一个缺少 e ,第二个缺少 P 。还要注意角色的情况。因此,如果我有一个按顺序排列所有字母的巨大物体,然后检查下一个字母并进行比较?

If we see that, there is one letter is missing from each of the arrays. First one has e missing and the second one has P missing. Care to be taken for the case of the character as well. So, if I have a huge Object which has all the letters in order, and check them for the next ones, and compare?

我对使用哪种方法完全感到困惑跟随!这是我到目前为止所得到的:

I am totally confused on what approach to follow! This is what I have got till now:

var chars = ("abcdefghijklmnopqrstuvwxyz"+"abcdefghijklmnopqrstuvwxyz".toUpperCase()).split("");

所以这给了我:

["a","b","c","d","e","f","g","h","i","j","k","l","m",
 "n","o","p","q","r","s","t","u","v","w","x","y","z",
 "A","B","C","D","E","F","G","H","I","J","K","L","M",
 "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

很棒。现在我的问题是,我喜欢如何检查范围内的缺失字符?

Which is awesome. Now my question is, how do I like check for the missing character in the range? Some kind of forward lookup?

我尝试过这样的事情:


  • 查找源数组中的 indexOf 起始值。

  • 将它们与每个数组进行比较。

  • 如果比较失败,返回原始数组中的那个?

  • Find the indexOf starting value in the source array.
  • Compare it with each of them.
  • If the comparison failed, return the one from the original array?

推荐答案

我认为更好的方法是检查数组中的每个元素是否下一个字符是下一个字符:

I think that a much better way is to check for each element in your array if the next element is the next char:

function checkMissingChar(ar) {
  for (var i = 1; i < ar.length; i++) {
    if (ar[i].charCodeAt(0) == ar[i-1].charCodeAt(0)+1) {
      // console.log('all good');
    } else {
      return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
    }
  }
  return true;
}

var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']

console.log(checkMissingChar(a));
console.log(checkMissingChar(b));


不是我开始检查带有第二个项目的数组,因为我将它与之前的项目(数组中的第一个)进行了比较。

Not that I start to check the array with the second item because I compare it to the item before (the first in the Array).

这篇关于如何找到数组中缺少的下一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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