JavaScript 中的表达性词语问题案例

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/8 6:04:17

有时人们会重复字母来表达额外的感觉,例如"hello" −> "heeellooo","hi" −> "hiiii"。在类似"heeellooo"的字符串中,我们有一组相邻字母,它们都是相同的:"h"、"eee"、"ll"、"ooo"。

对于某个给定的字符串 S,如果可以通过以下扩展操作的任意次数应用使查询词等于 S,则该查询词是可伸缩的:选择一个由字符 c 组成的组,并向该组添加一定数量的字符 c,使该组的大小为 3 或更多。

例如,从"hello"开始,我们可以对组"o"进行扩展以获得"hellooo",但是由于组"oo"的大小小于 3,因此我们无法获得"helloo"。此外,我们还可以进行另一个扩展,例如"ll"−> "lllll"得到"helllllooo"。如果 S = "helllllooo",那么查询词"hello"会因为这两个扩展操作而变得可拉伸:query = "hello" −> "hellooo" −> "helllllooo" = S。

给定一个查询词列表,我们需要返回可拉伸单词的数量。

例如 −

如果输入字符串是 −

const str = 'heeellooo';

单词列表为 −

const words = ["hello", "hi", "helo"];

输出应为 −

const output = 1

示例

其代码为 −

const str = 'heeellooo';
const words = ["hello", "hi", "helo"];
const extraWords = (str, words) => {
   let count = 0;
   for (let w of words) {
      let i = 0;
      let j = 0;
      for (; i < str.length && j < w.length && w[j] === str[i];) {
         let lenS = 1;
         let lenW = 1;
         for (; i+lenS < str.length && str[i+lenS] === str[i]; lenS++);
         for (; j+lenW < w.length && w[j+lenW] === w[j]; lenW++);
         if (lenS < lenW || lenS > lenW && lenS < 3) break;
         i += lenS;
         j += lenW;
      }
      if (i === str.length && j === w.length) {
         count++;
      }
   }
   return count;
}
console.log(extraWords(str, words));

输出

控制台中的输出将是 −

1

相关文章


有用资源