11function isValidAlphaAbbreviation ( word : string , abbr : string ) : boolean {
2-
32 if ( word . length < 1 || word . length > 25 ) return false ;
43 if ( abbr . length < 1 || abbr . length > 15 ) return false ;
54 if ( ! / ^ [ a - z ] + $ / . test ( word ) ) return false ;
65 if ( ! / ^ [ a - z ] + $ / . test ( abbr ) ) return false ;
7- if ( abbr . length > word . length ) return false ;
8-
9- let built = "" ;
10- let i = 0 ;
11-
12- while ( i < word . length ) {
13- const ch = word [ i ] ;
14-
15- built += ch ;
16- i ++ ;
17-
18- if ( i < word . length ) {
19- const skip = ch . charCodeAt ( 0 ) - 96 ;
20- i += skip ;
6+
7+ let wordIndex : number = 0 ;
8+ let i : number = 0 ;
9+
10+ while ( i < abbr . length && wordIndex < word . length ) {
11+ const ch : string = abbr [ i ] ; // Process abbreviation, not word
12+
13+ if ( word [ wordIndex ] === ch ) {
14+ // Literal character match
15+ wordIndex ++ ;
16+ i ++ ;
17+ } else {
18+ // Character represents a number - skip that many characters
19+ const skip : number = ch . charCodeAt ( 0 ) - 96 ; // a=1, b=2, etc.
20+ wordIndex += skip ;
21+ i ++ ;
2122 }
2223 }
23-
24- return built === abbr ;
25- }
26- console . log ( isValidAlphaAbbreviation ( "abbreviation" , "acefn" ) ) ; // true
27- console . log ( isValidAlphaAbbreviation ( "abbreviation" , "acehn" ) ) ; // false
28- console . log ( isValidAlphaAbbreviation ( "abbreviation" , "acgn" ) ) ; // false
29- console . log ( isValidAlphaAbbreviation ( "internationalization" , "imzdn" ) ) ; // true
30- console . log ( isValidAlphaAbbreviation ( "internationalization" , "inz" ) ) ; // false
24+
25+ return wordIndex === word . length && i === abbr . length ;
26+ }
0 commit comments