如何检测每个连续字符与前一个字符相差最小字母差的字符序列(1)

How to detect char sequences where each successive char differs from the previous one by minimal alphabetical difference (1)?

本文关键字:字符 检测 何检测 连续 一个      更新时间:2023-09-26

我想检测每个连续字符与前一个字符相差1的字符序列,其中1是其"字母差"。在标准字母表中,index("b")-index("a")=1, index("z")-index("y")=1, index("z")-index("x")=2,依此类推。我想要的是用它的第一个和最后一个字符替换这样的序列,删除介于两者之间的所有字符。请注意,如果在这样的序列中只有两个字符,则不需要替换。如果顺序相反,则不需要替换,例如"dcba"
例如,

"dabcehklopqrsafxwvu012345678910210"  

应该转换为

"dacehklosafxwvu0910210"  

有趣的是,昨天我解决了完全相同的问题:)。

尝试以下解决方案:

var str = "dabcehklopqrsafxwvu012345678910210";
var res = Array.prototype.reduce.call(str, function(acc, item, index, strAr) {
  var pushItem = 
      //first item always included
      index === 0 || 
      // last item always included
      index === strAr.length - 1 || 
      // include the first item in sequence
      strAr[index - 1].charCodeAt(0) + 1 !== item.charCodeAt(0) ||
      // include the last item in sequence
      strAr[index + 1].charCodeAt(0) - 1 !== item.charCodeAt(0)
  if (pushItem) {
    acc += item;
  }
  return acc;
}, '');
console.log(res); // prints "dacehklosafxwvu0910210"

查看工作演示。

单循环解决方案

var code = 'dabcehklopqrsafxwvu012345678910210',
    result = '',
    i = 0, l;
for (i = 0, l = code.length; i < l; i++) {
    result += 
        i > 0 &&
        i + 1 < l && 
        code.charCodeAt(i - 1) + 1 === code.charCodeAt(i) &&
        code.charCodeAt(i) + 1 === code.charCodeAt(i + 1) ?
            '' : 
            code[i];
}
document.write(result);

我认为您键入的示例答案不正确。。。因为你们彼此之间还有kl。。。

不管怎样,你的代码应该像下面这样:

var x = "dabcehklopqrsafxwvu012345678910210";
    var z = x;
    for (var i = 1; i < x.length - 1; i++)
        if (x.charCodeAt(i) == x.charCodeAt(i + 1) - 1) {
            x = x.replace(x.charAt(i) + x.charAt(i + 1), x.charAt(i));
        }
    alert(x);

这里的问题是,如果12345应该是135,在你的样本中,klopq变成了klo。。。?