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
廣告