Valid Word Abbreviation
Here’s a code snippet to check if a given abbreviation abbr
is valid for a particular word word
:
|
|
Explanation
- We iterate through both the word and abbreviation using indices
i
andj
. - If the current character in
abbr
is a letter, we check if it matches the corresponding character inword
. If not, we returnFalse
. - If the current character in
abbr
is a digit, we collect the subsequent digits to form a number, but we make sure the number doesn’t start with0
. - We skip the corresponding number of characters in
word
as indicated by the collected number. - Finally, we check if both
i
andj
reached the end of theword
andabbr
respectively, returningTrue
if they have, andFalse
otherwise.