[LeetCode] 291. Word Pattern II 词语模式 II
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:
- pattern =
"abab", str ="redblueredblue"should return true. - pattern =
"aaaa", str ="asdasdasdasd"should return true. - 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的更多相关文章
- LeetCode 290. Word Pattern (词语模式)
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
- LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)
翻译 给定一个模式,和一个字符串str.返回str是否符合同样的模式. 这里的符合意味着全然的匹配,所以这是一个一对多的映射,在pattern中是一个字母.在str中是一个为空的单词. 比如: pat ...
- [LeetCode] 290. Word Pattern 单词模式
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
- 290. Word Pattern 单词匹配模式
[抄题]: Given a pattern and a string str, find if str follows the same pattern. Here follow means a fu ...
- [LeetCode] Word Pattern II 词语模式之二
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
- Leetcode solution 291: Word Pattern II
Problem Statement Given a pattern and a string str, find if str follows the same pattern. Here follo ...
- [LeetCode] 290. Word Pattern 词语模式
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
- leetcode 290. Word Pattern 、lintcode 829. Word Pattern II
290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...
- 291. Word Pattern II
题目: Given a pattern and a string str, find if str follows the same pattern. Here follow means a full ...
随机推荐
- [Reproduced] How to Improve Code Quality?
How to Improve Code Quality? Ref: https://www.perforce.com/blog/sca/what-code-quality-and-how-improv ...
- 微信小程序和APP优劣势大对比
小程序的优势: 1. 无需下载,随走随关 2. 功能丰富,体验更简便 3. 接口众多,可以进行不断的开发 4. 流量入口大,背靠日活9.6亿的微信 5. 有强大的微信生态环境 小程序对比APP的好处: ...
- P1972 [SDOI2009]HH的项链[离线+树状数组/主席树/分块/模拟]
题目背景 无 题目描述 HH 有一串由各种漂亮的贝壳组成的项链.HH 相信不同的贝壳会带来好运,所以每次散步完后,他都会随意取出一段贝壳,思考它们所表达的含义.HH 不断地收集新的贝壳,因此,他的项链 ...
- 《exception》第九次团队作业:Beta冲刺与验收准备(第三天)
一.项目基本介绍 项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 作业链接地址 团队名称 Exception 作业学习目标 1.掌握软件黑盒测试技术:2.学会编制软件项目 ...
- QPS、TPS、PV、UV、IP
QPS TPS PV UV IP GMV RPS QPS.TPS.PV.UV.GMV.IP.RPS等各种名词,外行看起来很牛X,实际上每个程序员都是必懂知识点.下面我来一一解释一下. QPS Quer ...
- Django 中使用redis
Django使用redis 方式一,使用Django-redis模块 #安装: pip3 install django-redis CACHES = { "default": ...
- Learning Vector Quantization
学习矢量量化. k近邻的缺点是你需要维持整个数据集的训练. 学习矢量量化算法(简称LVQ)是一种人工神经网络算法,它允许你选择要挂在多少个训练实例上,并精确地了解这些实例应该是什么样子. LVQ的表示 ...
- ctx控制超时的使用
cancel package main import ( "context" "fmt" "time" ) func gen(ctx con ...
- LOJ P10018 数的划分 题解
每日一题 day52 打卡 Analysis 这道题直接搜索会TLE到**,但我们发现有很多没有用的状态可以删去,比如 1,1,5; 1,5,1; 5,1,1; 所以很容易想到一个优化:按不下降的顺序 ...
- Greenplum 6 新功能 在线扩容工具GPExpand (转载)
Gpexpand是Greenplum数据库的扩容工具,可以为集群增加新节点从而可以存储更多的数据,提供更高的计算能力.Greenplum 5及之前,集群扩容需要停机增加新节点,然后对表数据做重分布.因 ...