You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ES6原生JavaScript找出无连续重复的字母集合

解决方案

思路

要找出从未在任意单词中连续出现的字母,核心分两步走:

  1. 先定位所有出现过连续重复的字母
  2. 从目标字母集合(要么是单词中出现过的所有字母,要么是全部英文字母)里排除上述重复字母,剩下的就是结果。

代码实现(针对单词中出现过的字母)

function findNonRepeatingConsecutiveLetters(words) {
  // 收集所有有连续重复记录的字母
  const repeatedChars = new Set();
  const consecutiveRegex = /(.)\1+/g;
  
  words.forEach(word => {
    let match;
    // 遍历所有连续重复的匹配项
    while ((match = consecutiveRegex.exec(word)) !== null) {
      repeatedChars.add(match[1]);
    }
  });

  // 收集单词中出现过的所有字母(自动去重)
  const allUsedChars = new Set();
  words.forEach(word => [...word].forEach(char => allUsedChars.add(char)));

  // 过滤出从未连续重复的字母
  return [...allUsedChars].filter(char => !repeatedChars.has(char));
}

// 测试用例
const testWords = ["apple", "banana", "cherry", "date", "egg", "fox"];
console.log(findNonRepeatingConsecutiveLetters(testWords));
// 输出: ["a", "b", "c", "h", "e", "r", "y", "d", "t", "f", "o", "x"]

代码说明

  • 正则/(.)\1+/g专门匹配任意连续重复的字符,通过Set去重后得到所有有连续重复记录的字母。
  • 遍历所有单词的每个字符,存入Set得到所有出现过的字母(自动去重)。
  • 用filter方法求两个集合的差集,最终得到从未连续出现的字母。

扩展:针对全部英文字母(无论是否在单词中出现)

如果需要覆盖所有英文字母(不管是否在输入单词里出现),只需修改字母集合的生成逻辑:

// 生成全部英文字母(小写+大写)
function getAllEnglishLetters() {
  const letters = [];
  // 小写a-z
  for (let i = 97; i <= 122; i++) letters.push(String.fromCharCode(i));
  // 大写A-Z
  for (let i = 65; i <= 90; i++) letters.push(String.fromCharCode(i));
  return new Set(letters);
}

function findNonRepeatingConsecutiveLetters(words) {
  const repeatedChars = new Set();
  const consecutiveRegex = /(.)\1+/g;
  
  words.forEach(word => {
    let match;
    while ((match = consecutiveRegex.exec(word)) !== null) {
      repeatedChars.add(match[1]);
    }
  });

  const allLetters = getAllEnglishLetters();
  return [...allLetters].filter(char => !repeatedChars.has(char));
}

内容的提问来源于stack exchange,提问作者Eric Hepperle - CodeSlayer2010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:05:26