Word Pattern Problem


Description

LeetCode Problem 290.

Given a pattern and a string s, find if sfollows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

Example 1:

1
2
Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Example 2:

1
2
Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Example 3:

1
2
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

Example 4:

1
2
Input: pattern = "abba", s = "dog dog dog dog"
Output: false

Constraints:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lower-case English letters and spaces ‘ ‘.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int i = 0, j = 0;
        map<char, string> ht;
        map<string, char> ht2;
        bool match = true;
        string s;
        
        while (!str.empty()) {
            size_t p = str.find(' ');
            int len = str.size();
            s = str.substr(0, p);
            str = str.substr(p+1, len-p-1);
            
            if (pattern.size() < i+1) {
                match = false;
                break;
            }
            
            if (ht.find(pattern[i]) == ht.end()) {
                if (ht2.find(s) != ht2.end()) {
                    match = false;
                    break;
                }
                ht[pattern[i]] = s;
                ht2[s] = pattern[i];
            } else {
                if (ht[pattern[i]] != s) {
                    match = false;
                    break;
                }
            }
            i ++;
            if (p == -1) {
                if (i < pattern.size()) {
                    match = false;
                }
                break;
            }
        }
        
        return match;
    }
};




Related Posts

X Of A Kind In A Deck Of Cards Problem

LeetCode 914. In a deck of cards, each card has...

Word Subsets Problem

LeetCode 916. You are given two string arrays words1 and...

Vowel Spellchecker Problem

LeetCode 966. Given a wordlist, we want to implement a...

Verifying An Alien Dictionary Problem

LeetCode 953. In an alien language, surprisingly, they also use...

Unique Morse Code Words Problem

LeetCode 804. International Morse Code defines a standard encoding where...

Unique Email Addresses Problem

LeetCode 929. Every valid email consists of a local name...