Skip to content

Commit b4c06b1

Browse files
committed
Add solution #408
1 parent edd396e commit b4c06b1

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,7 @@
396396
405|[Convert a Number to Hexadecimal](./solutions/0405-convert-a-number-to-hexadecimal.js)|Easy|
397397
406|[Queue Reconstruction by Height](./solutions/0406-queue-reconstruction-by-height.js)|Medium|
398398
407|[Trapping Rain Water II](./solutions/0407-trapping-rain-water-ii.js)|Hard|
399+
408|[Valid Word Abbreviation](./solutions/0408-valid-word-abbreviation.js)|Easy|
399400
409|[Longest Palindrome](./solutions/0409-longest-palindrome.js)|Easy|
400401
410|[Split Array Largest Sum](./solutions/0410-split-array-largest-sum.js)|Hard|
401402
412|[Fizz Buzz](./solutions/0412-fizz-buzz.js)|Easy|
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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

Comments
 (0)