|
| 1 | +/** |
| 2 | + * 408. Valid Word Abbreviation |
| 3 | + * https://leetcode.com/problems/valid-word-abbreviation/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * A string can be abbreviated by replacing any number of non-adjacent, non-empty substrings |
| 7 | + * with their lengths. The lengths should not have leading zeros. |
| 8 | + * |
| 9 | + * For example, a string such as "substitution" could be abbreviated as (but not limited to): |
| 10 | + * - "s10n" ("s ubstitutio n") |
| 11 | + * - "sub4u4" ("sub stit u tion") |
| 12 | + * - "12" ("substitution") |
| 13 | + * - "su3i1u2on" ("su bst i t u ti on") |
| 14 | + * - "substitution" (no substrings replaced) |
| 15 | + * |
| 16 | + * The following are not valid abbreviations: |
| 17 | + * - "s55n" ("s ubsti tutio n", the replaced substrings are adjacent) |
| 18 | + * - "s010n" (has leading zeros) |
| 19 | + * - "s0ubstitution" (replaces an empty substring) |
| 20 | + * |
| 21 | + * Given a string word and an abbreviation abbr, return whether the string matches the given |
| 22 | + * abbreviation. |
| 23 | + * |
| 24 | + * A substring is a contiguous non-empty sequence of characters within a string. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {string} word |
| 29 | + * @param {string} abbr |
| 30 | + * @return {boolean} |
| 31 | + */ |
| 32 | +var validWordAbbreviation = function(word, abbr) { |
| 33 | + let wordIndex = 0; |
| 34 | + let abbrIndex = 0; |
| 35 | + |
| 36 | + while (wordIndex < word.length && abbrIndex < abbr.length) { |
| 37 | + if (word[wordIndex] === abbr[abbrIndex]) { |
| 38 | + wordIndex++; |
| 39 | + abbrIndex++; |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + if (abbr[abbrIndex] < '0' || abbr[abbrIndex] > '9') return false; |
| 44 | + if (abbr[abbrIndex] === '0') return false; |
| 45 | + |
| 46 | + let num = 0; |
| 47 | + while (abbrIndex < abbr.length && /[0-9]/.test(abbr[abbrIndex])) { |
| 48 | + num = num * 10 + Number(abbr[abbrIndex]); |
| 49 | + abbrIndex++; |
| 50 | + } |
| 51 | + wordIndex += num; |
| 52 | + } |
| 53 | + |
| 54 | + return wordIndex === word.length && abbrIndex === abbr.length; |
| 55 | +}; |
0 commit comments