是另一个的字符串子序列。解决方案未被接受,但在我的 IDE 中运行良好

Is string subsequence of another. Solution not accepted, but runs fine in my IDE

我正在学习 JavaScript 并且正在处理一些 DSA 问题。这是我要解决的问题:

Write a function isSubsequence which takes in two strings and checks whether the characters in the first string form a subsequence of the characters in the second string. In other words, the function should check whether the characters in the first string appear somewhere in the second string, without their order changing

  1. isSubsequence('hello','hello world') //true
  2. isSubsequence('sing','sting') //true
  3. isSubsequence('abc','abracadabra') //true
  4. isSubsequence('abc', 'acb') //false

这是我的代码:

const isSubsequence = (str1, str2) => {
  const createCharObj = (string) => {
    let outputObj = {};
    for (let i = 0; i < string.length; i++) {
      if (outputObj[string[i]]) {
        outputObj[string[i]]++;
      } else {
        outputObj[string[i]] = 1;
      }
    }
    return outputObj;
  };
  let charObj1 = createCharObj(str1);
  let charObj2 = createCharObj(str2);
  let compare = "";

  for (let key in charObj2) {
    if (charObj2[key] < charObj1[key]) {
      return false;
    } else {
      let exceed = charObj1[key];
      let i = 0;
      while (i < exceed) {
        compare += key;
        i++;
      }
    }
  }
  return compare === str1;
};

console.log(isSubsequence("hello", "hello world"));
console.log(isSubsequence("sing", "sting"));
console.log(isSubsequence("abc", "abracadabra"));
console.log(isSubsequence("abc", "acb"));

我明白我的解决方案效率不高,但我相信逻辑是正确的。

但是,当我在 Udemy 的 IDE 上 运行 它时,我收到一条错误消息:

expected false to be true

然而,当我在 VS 代码上 运行 时,没有任何问题。请告诉我哪里做错了。

你的算法不正确。代码挑战网站 (Udemy) 也在为您的代码提供 其他 输入,对于其中一些(不是您列出的那些),您的代码 return 是错误的结果.

假设如果第二个字符串中的字母对应于第一个字符串中的字母,则它必须也是正确顺序的字母。这不一定是第一次在第二个字符串中遇到这个字符。

例如,您的代码将 return 此输入的错误结果:

console.log(isSubsequence("abc", "acabc"));

这是因为在第二个字符串中,“c”的第一次出现在“b”的第一次出现之前,但它应该忽略第一个“c”。

提示:

主要迭代应该在 第一个 字符串上,而不是第二个。

一旦在第二个字符串中找到第一个字符串中的某个字符,在下一次搜索中应该完全忽略第二个字符串中该字符之前的所有字符。

剧透解决方案:

const isSubsequence = (str1, str2) => { let j = -1; for (let ch of str1) { j = str2.indexOf(ch, j + 1); if (j === -1) return false; } return true; };