[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 ...
随机推荐
- jQuery 查找和过滤
通常情况下选择器可以直接定位到我们想要的元素,但是,当我们拿到一个jQuery对象后,还可以以这个对象为基准,进行查找和过滤. 最常见的查找是在某个节点的所有子节点中查找,使用find()方法,它本身 ...
- jsp解决大文件断点续传
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...
- WinDbg常用命令系列---!envvar
!envvar 简介 !envvar扩展命令显示特定环境变量的值. 使用形式 !envvar Variable 参数 Variable指定显示其值的环境变量.变量不区分大小写. 环境 Windows ...
- 使用for循环签到嵌套制作直角三角形
注意代码的运行顺序: for(i = 0 ; i<9 ; i++){ for(j = 0 ; j<i-1 ; j++){ document.write("*")//** ...
- graphql-query-rewriter 无缝处理graphql 变更
graphql-query-rewriter 是一个graphql schema 变动重写的中间件,可以帮助我们解决在版本变动,查询实体变动 是的问题,从目前已知的技术中我们可选的方案有以下处理变动的 ...
- Dart和JavaScript对比小结
作为一名web前端来入门dart,新语言和我们熟悉的js有所差异,写dart的过程中容易受到原有思维的影响,这里把dart和js做一个对比总结,方便查找和熟悉. 变量声明 var 关键字 dart和j ...
- 51、Spark Streaming之输入DStream和Receiver详解
输入DStream代表了来自数据源的输入数据流.在之前的wordcount例子中,lines就是一个输入DStream(JavaReceiverInputDStream), 代表了从netcat(nc ...
- outlook 修改视图
- PHP strtok() 函数
我们仅在第一次调用 strtok() 函数时使用了 string 参数.在首次调用后,该函数仅需要 split 参数,这是因为它清楚自己在当前字符串中所在的位置. 如需分割一个新的字符串,请再次调用带 ...
- 移动端点击事件兼容问题,在pc端可以点,在手机上不可以点
ms-click="showCodeExplain()" onClick="javascript:;" 在点击事件后面加上onClick="javas ...