|
| 1 | +/** |
| 2 | + * 809. Expressive Words |
| 3 | + * https://leetcode.com/problems/expressive-words/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Sometimes people repeat letters to represent extra feeling. For example: |
| 7 | + * - "hello" -> "heeellooo" |
| 8 | + * - "hi" -> "hiiii" |
| 9 | + * |
| 10 | + * In these strings like "heeellooo", we have groups of adjacent letters that are all the |
| 11 | + * same: "h", "eee", "ll", "ooo". |
| 12 | + * |
| 13 | + * You are given a string s and an array of query strings words. A query word is stretchy |
| 14 | + * if it can be made to be equal to s by any number of applications of the following extension |
| 15 | + * operation: choose a group consisting of characters c, and add some number of characters |
| 16 | + * c to the group so that the size of the group is three or more. |
| 17 | + * |
| 18 | + * For example, starting with "hello", we could do an extension on the group "o" to get |
| 19 | + * "hellooo", but we cannot get "helloo" since the group "oo" has a size less than three. |
| 20 | + * Also, we could do another extension like "ll" -> "lllll" to get "helllllooo". If |
| 21 | + * s = "helllllooo", then the query word "hello" would be stretchy because of these two |
| 22 | + * extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s. |
| 23 | + * |
| 24 | + * Return the number of query strings that are stretchy. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {string} s |
| 29 | + * @param {string[]} words |
| 30 | + * @return {number} |
| 31 | + */ |
| 32 | +var expressiveWords = function(s, words) { |
| 33 | + let result = 0; |
| 34 | + |
| 35 | + for (const word of words) { |
| 36 | + if (verify(s, word)) { |
| 37 | + result++; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | +}; |
| 43 | + |
| 44 | +function verify(s, word) { |
| 45 | + let i = 0; |
| 46 | + let j = 0; |
| 47 | + |
| 48 | + while (i < s.length && j < word.length) { |
| 49 | + if (s[i] !== word[j]) return false; |
| 50 | + |
| 51 | + const char = s[i]; |
| 52 | + let sCount = 0; |
| 53 | + |
| 54 | + while (i < s.length && s[i] === char) { |
| 55 | + sCount++; |
| 56 | + i++; |
| 57 | + } |
| 58 | + |
| 59 | + let wordCount = 0; |
| 60 | + |
| 61 | + while (j < word.length && word[j] === char) { |
| 62 | + wordCount++; |
| 63 | + j++; |
| 64 | + } |
| 65 | + |
| 66 | + if (wordCount > sCount) return false; |
| 67 | + if (sCount > wordCount && sCount < 3) return false; |
| 68 | + } |
| 69 | + |
| 70 | + return i === s.length && j === word.length; |
| 71 | +} |
0 commit comments