【问题标题】:Find the first none-repeated character in a string, what are the mistakes here?找到字符串中第一个不重复的字符,这里的错误是什么?
【发布时间】:2021-01-12 13:38:45
【问题描述】:

我正在做一些练习。问题是在字符串中找到第一个不重复的字符。 我的想法是:将字符串转换为数组。将 array[0] 分配给一个新变量,并从 array 中删除这个 array[0]。检查这个新数组是否包含这个变量,如果没有,返回这个变量。否则,使用过滤器删除相同的值元素并获取一个新数组。重复这个过程。代码如下。

const NoneReChar = (str) => {
  let tempArr = str.split('');
  let start = tempArr[0];
  while (true) {
    tempArr.shift();
    if (!tempArr.includes(start)) {
      return start;
    } else {
      tempArr.filter(char => char !== start);
      start = tempArr[0];
    }
  }
}
console.log(NoneReChar("aaaabbbeccc"))

我期待输出'e',但我一直得到'a'......我在这里犯的错误在哪里?

【问题讨论】:

  • tempArr.filter(char => char !== start)不会改变tempArr,它返回一个新的过滤数组,尝试将tempArr分配给.filter()的返回值

标签: javascript arrays string filter


【解决方案1】:

Array.filter() 方法不会改变原始数组。您需要将过滤器的结果分配给tempArr

tempArr = tempArr.filter(char => char !== start);

例子:

const NoneReChar = (str) => {
  let tempArr = str.split('');
  let start = tempArr[0];
  while (true) {
    tempArr.shift();
    if (!tempArr.includes(start)) {
      return start;
    } else {
      tempArr = tempArr.filter(char => char !== start);
      start = tempArr[0];
    }
  }
}
console.log(NoneReChar("aaaabbbeccc"))

但是,您不处理未找到的情况。要处理它而不是 true,while 子句应该在数组为空时停止:

const NoneReChar = (str) => {
  let tempArr = str.split('');
  let start = tempArr[0];
  
  while (tempArr.length) {
    tempArr.shift();
    if (!tempArr.includes(start)) {
      return start;
    } else {
      tempArr = tempArr.filter(char => char !== start);
      start = tempArr[0];
    }
  }
  
  return null;
}
console.log(NoneReChar("aabbcc"))

另一个选项是比较过滤前后数组的长度。如果长度相同,则该项不重复:

const NoneReChar = (str) => {
  let tempArr = str.split('');
  
  while (tempArr.length) {
    const [start, ...rest] = tempArr; // take the 1st item and the rest
    
    tempArr = rest.filter(char => char !== start); // filter out start
    
    if(tempArr.length === rest.length) { // check current and previous arrays, and if the length still matches, start didn't appear again
      return start;
    }
  }
  
  return null;
}
console.log(NoneReChar("aabzbcc"))

【讨论】:

    【解决方案2】:
    const NoneReChar = (str) => {
          const tempArr = str.split('');
          let result = 'Not Found';
          for (let index = 0; index < tempArr.length; index++) {
            const firstIndex = tempArr.indexOf(tempArr[index]);
            const lastIndex = tempArr.lastIndexOf(tempArr[index]);
            if (firstIndex === lastIndex) {
              result = tempArr[index];
              break;
            }
          }
          return result;
        }
        console.log(NoneReChar("aaaabbbeccc"));
    

    【讨论】:

      猜你喜欢
      • 2011-01-18
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      • 2017-09-22
      • 2011-11-02
      相关资源
      最近更新 更多