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

Find Duplicate Subtrees Problem

LeetCode 652. Given the rootof a binary tree, return all...

Delete And Earn Problem

LeetCode 740. You are given an integer array nums. You...

Degree Of An Array Problem

LeetCode 697. Given a non-empty array of non-negative integers nums,...

Custom Sort String Problem

LeetCode 791. You are given two strings order and s....

Basic Calculator IV Problem

LeetCode 770. Given an expression such as expression = “e...

Sort Characters By Frequency Problem

LeetCode 451. Given a string s, sort it in decreasing...