290. Word Pattern
Tags:
Easy
Skills:
Hashmap
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu kiểm tra một chuỗi s có tuân theo mẫu pattern hay không, tức là có tồn tại ánh xạ một-một (bijection) giữa từng ký tự của pattern và từng từ trong s ?
Approach
s thành mảng các từ bảng hàm split(' ') pattern khác số từ trong s , return false ngay vì không thể ánh xạ một -mộtpattern_to_word : Ánh xạ ký tự trong pattern sang từ trong s word_to_pattern : Ánh xạ ký tự trong s sang ký tự trong pattern false true Solution
1function wordPattern(pattern: string, s: string): boolean {
2 const words = s.split(' ');
3 if (words.length !== pattern.length) return false;
4 const word_to_pattern: Map<string, string> = new Map();
5 const pattern_to_word: Map<string, string> = new Map();
6
7 for (let i = 0; i < pattern.length; i++) {
8 const char = pattern[i];
9 const word = words[i];
10
11 if (word_to_pattern.has(word) && word_to_pattern.get(word) !== char) {
12 return false
13 }
14
15 if (pattern_to_word.has(char) && pattern_to_word.get(char) !== word) {
16 return false
17 }
18
19 word_to_pattern.set(word, char);
20 pattern_to_word.set(char, word)
21 }
22
23 return true;
24};