JavaScript中的表达词问题案例
有时人们会重复字母来代表额外的感觉,例如“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