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