Skip to content

Latest commit

 

History

History

291

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given a pattern and a string s, return true if s matches the pattern.

A string s matches a pattern if there is some bijective mapping of single characters to strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings.

 

Example 1:

Input: pattern = "abab", s = "redblueredblue"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "red"
'b' -> "blue"

Example 2:

Input: pattern = "aaaa", s = "asdasdasdasd"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "asd"

Example 3:

Input: pattern = "abab", s = "asdasdasdasd"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "a"
'b' -> "sdasd"
Note that 'a' and 'b' cannot both map to "asd" since the mapping is a bijection.

Example 4:

Input: pattern = "aabb", s = "xyzabcxzyabc"
Output: false

 

Constraints:

  • 1 <= pattern.length, s.length <= 20
  • pattern and s consist of only lower-case English letters.

Companies:
Uber

Related Topics:
Hash Table, String, Backtracking

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/word-pattern-ii/
// Author: github.com/lzl124631x
// Time: O(PS)
// Space: O(S)
class Solution {
public:
    bool wordPatternMatch(string p, string s) {
        unordered_map<char, string> m;
        unordered_set<string> seen;
        function<bool(int,int)> dfs = [&](int i, int j) {
            if (i == p.size()) return j == s.size();
            if (m.count(p[i])) {
                auto t = m[p[i]];
                return s.substr(j, t.size()) == t && dfs(i + 1, j + t.size());
            } else {
                string t;
                for (int k = j; k < s.size(); ++k) {
                    t += s[k];
                    if (seen.count(t)) continue;
                    seen.insert(t);
                    m[p[i]] = t;
                    if (dfs(i + 1, k + 1)) return true;
                    seen.erase(t);
                    m.erase(p[i]);
                }
            }
            return false;
        };
        return dfs(0, 0);
    }
};