File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed
solution/0200-0299/0290.Word Pattern Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change @@ -262,4 +262,33 @@ public class Solution {
262
262
263
263
<!-- solution: end -->
264
264
265
+ <!-- solution: start -->
266
+
267
+ ### Solution 2
268
+
269
+ <!-- tabs: start -->
270
+
271
+ #### TypeScript
272
+
273
+ ``` ts
274
+ function wordPattern(pattern : string , s : string ): boolean {
275
+ const hash: Record <string , string > = Object .create (null );
276
+ const arr = s .split (/ \s + / );
277
+
278
+ if (pattern .length !== arr .length || new Set (pattern ).size !== new Set (arr ).size ) return false ;
279
+
280
+ for (let i = 0 ; i < pattern .length ; i ++ ) {
281
+ hash [pattern [i ]] ?? = arr [i ];
282
+
283
+ if (hash [pattern [i ]] !== arr [i ]) return false ;
284
+ }
285
+
286
+ return true ;
287
+ }
288
+ ```
289
+
290
+ <!-- tabs: end -->
291
+
292
+ <!-- solution: end -->
293
+
265
294
<!-- problem: end -->
Original file line number Diff line number Diff line change
1
+ function wordPattern ( pattern : string , s : string ) : boolean {
2
+ const hash : Record < string , string > = Object . create ( null ) ;
3
+ const arr = s . split ( / \s + / ) ;
4
+
5
+ if ( pattern . length !== arr . length || new Set ( pattern ) . size !== new Set ( arr ) . size ) return false ;
6
+
7
+ for ( let i = 0 ; i < pattern . length ; i ++ ) {
8
+ hash [ pattern [ i ] ] ??= arr [ i ] ;
9
+
10
+ if ( hash [ pattern [ i ] ] !== arr [ i ] ) return false ;
11
+ }
12
+
13
+ return true ;
14
+ }
You can’t perform that action at this time.
0 commit comments