JavaScript中表达性单词问题案例
有时人们重复字母来表达额外的感情,例如“hello” -> “heeellooo”,“hi” -> “hiiii”。在像“heeellooo”这样的字符串中,我们有由相邻的相同字符组成的组:“h”,“eee”,“ll”,“ooo”。
对于给定的字符串S,如果可以通过任意次数的以下扩展操作将其变成等于S,则查询词是可拉伸的:选择一个由字符c组成的组,并向该组添加任意数量的字符c,使得该组的大小为3或更大。
例如,从“hello”开始,我们可以对组“o”进行扩展得到“hellooo”,但我们无法得到“helloo”,因为组“oo”的大小小于3。此外,我们可以进行另一个扩展,例如“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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP