Given a pattern and a string str, find if str follows the same pattern.

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

Examples:

  1. pattern = "abab", str = "redblueredblue" should return true.
  2. pattern = "aaaa", str = "asdasdasdasd" should return true.
  3. pattern = "aabb", str = "xyzabcxzyabc" should return false.

Notes:
You may assume both pattern and str contains only lowercase letters.

290. Word Pattern 的拓展,区别是这里的单词字符串没有空格了,不能按空格把单词直接拆分出来。

可以用回溯法来判断每一种情况,用哈希表建立模式字符和单词之间的映射,还需要用变量p和r来记录当前递归到的模式字符和单词串的位置,在递归函数中,如果p和r分别等于模式字符串和单词字符串的长度,说明此时匹配成功结束了,返回ture,反之如果一个达到了而另一个没有,说明匹配失败了,返回false。

解法:回溯Backtracking

Python:

# Time:  O(n * C(n - 1, c - 1)), n is length of str, c is unique count of pattern,
# there are H(n - c, c - 1) = C(n - 1, c - 1) possible splits of string,
# and each one costs O(n) to check if it matches the word pattern.
# Space: O(n + c) class Solution(object):
def wordPatternMatch(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
w2p, p2w = {}, {}
return self.match(pattern, str, 0, 0, w2p, p2w) def match(self, pattern, str, i, j, w2p, p2w):
is_match = False
if i == len(pattern) and j == len(str):
is_match = True
elif i < len(pattern) and j < len(str):
p = pattern[i]
if p in p2w:
w = p2w[p]
if w == str[j:j+len(w)]: # Match pattern.
is_match = self.match(pattern, str, i + 1, j + len(w), w2p, p2w)
# Else return false.
else:
for k in xrange(j, len(str)): # Try any possible word
w = str[j:k+1]
if w not in w2p:
# Build mapping. Space: O(n + c)
w2p[w], p2w[p] = p, w;
is_match = self.match(pattern, str, i + 1, k + 1, w2p, p2w)
w2p.pop(w), p2w.pop(p);
if is_match:
break
return is_match  

C++:

class Solution {
public:
bool wordPatternMatch(string pattern, string str) {
unordered_map<char, string> m;
return helper(pattern, 0, str, 0, m);
}
bool helper(string pattern, int p, string str, int r, unordered_map<char, string> &m) {
if (p == pattern.size() && r == str.size()) return true;
if (p == pattern.size() || r == str.size()) return false;
char c = pattern[p];
for (int i = r; i < str.size(); ++i) {
string t = str.substr(r, i - r + 1);
if (m.count(c) && m[c] == t) {
if (helper(pattern, p + 1, str, i + 1, m)) return true;
} else if (!m.count(c)) {
bool b = false;
for (auto it : m) {
if (it.second == t) b = true;
}
if (!b) {
m[c] = t;
if (helper(pattern, p + 1, str, i + 1, m)) return true;
m.erase(c);
}
}
}
return false;
}
};  

C++:

class Solution {
public:
bool wordPatternMatch(string pattern, string str) {
unordered_map<char, string> m;
set<string> s;
return helper(pattern, 0, str, 0, m, s);
}
bool helper(string pattern, int p, string str, int r, unordered_map<char, string> &m, set<string> &s) {
if (p == pattern.size() && r == str.size()) return true;
if (p == pattern.size() || r == str.size()) return false;
char c = pattern[p];
for (int i = r; i < str.size(); ++i) {
string t = str.substr(r, i - r + 1);
if (m.count(c) && m[c] == t) {
if (helper(pattern, p + 1, str, i + 1, m, s)) return true;
} else if (!m.count(c)) {
if (s.count(t)) continue;
m[c] = t;
s.insert(t);
if (helper(pattern, p + 1, str, i + 1, m, s)) return true;
m.erase(c);
s.erase(t);
}
}
return false;
}
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 291. Word Pattern II 词语模式 II的更多相关文章

  1. LeetCode 290. Word Pattern (词语模式)

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  2. LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)

    翻译 给定一个模式,和一个字符串str.返回str是否符合同样的模式. 这里的符合意味着全然的匹配,所以这是一个一对多的映射,在pattern中是一个字母.在str中是一个为空的单词. 比如: pat ...

  3. [LeetCode] 290. Word Pattern 单词模式

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  4. 290. Word Pattern 单词匹配模式

    [抄题]: Given a pattern and a string str, find if str follows the same pattern. Here follow means a fu ...

  5. [LeetCode] Word Pattern II 词语模式之二

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  6. Leetcode solution 291: Word Pattern II

    Problem Statement Given a pattern and a string str, find if str follows the same pattern. Here follo ...

  7. [LeetCode] 290. Word Pattern 词语模式

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  8. leetcode 290. Word Pattern 、lintcode 829. Word Pattern II

    290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...

  9. 291. Word Pattern II

    题目: Given a pattern and a string str, find if str follows the same pattern. Here follow means a full ...

随机推荐

  1. ReentrantReadWriteLock中的锁降级

    锁降级指的是写锁降级为读锁. 因为读锁与读锁之间不互斥,如果是写锁与读锁或者是写锁与写锁就会互斥,所以由写锁变为读锁就降级了. 如果当前线程拥有写锁,然后将其释放,最后再获取读锁,这种并不能称之为锁降 ...

  2. Kotlin反射操纵构造方法与伴生对象

    反射操纵伴生对象: 先定义一个伴生对象: 然后咱们通过反射来调用一下它: 比较简单. 反射操纵构造方法: 先来定义一个类: 然后咱们通过反射来调用一个其中的方法,之前当然就得先来调用构造方法,由于我们 ...

  3. 使用树莓派GPIO控制继电器

      一.使用方法总结: VCC接+5v,GND接负,IN1接GPIO口, 二.然后使用Linux命令或者编程控制GPIO口高低电位即可,如:执行下列命令: gpio readall 列出所有针角 gp ...

  4. CSP-S 2019提高组训练 服务器需求

    时间限制:C/C++ 3秒 空间限制:C/C++ 262144K 题目描述 小多计划在接下来的n天里租用一些服务器,所有的服务器都是相同的.接下来n天中,第i天需要\(a_i\)台服务器工作,每台服务 ...

  5. 各大公司Java面试题收录含答案(整理版)持续中....

    本文分为17个模块,分别是:Java基础.容器.多线程.反射.对象拷贝.Java web.异常.网络.设计模式.算法.Spring/Spring MVC.Spring Boot/Spring Clou ...

  6. 转发: JS中的call()和apply()方法和区别 --小白变色记

    一.方法定义: apply:调用一个对象的一个方法,用另一个对象替换当前对象.例如:B.apply(A, arguments);即A对象应用B对象的方法. call:调用一个对象的一个方法,用另一个对 ...

  7. ccf算法模板

    bellman ford 算法求最短路径 #include <iostream> using namespace std; ; ; // 边, typedef struct Edge{ i ...

  8. (1)WIFI信号确定距离

    https://blog.csdn.net/PINGER0077/article/details/79482238 ESP8266不需要修改任何库 #include "ESP8266WiFi ...

  9. php 正则达达示中的模式修正符

    我们通过元字符和原子完成了正则表达示的入门.有一些特殊情况我们依然需要来处理.深圳dd马达 如果abc在第二行的开始处如何匹配?我不希望正则表达示特别贪婪的匹配全部,只匹配一部份怎么办? 这个时候,我 ...

  10. WinDbg常用命令系列---.write_cmd_hist (写命令历史记录)

    .write_cmd_hist 简介 .write_cmd_hist命令将调试器命令窗口的整个历史记录写入文件. 使用形式 .write_cmd_hist Filename 参数 Filename指定 ...