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. Nastya Hasn't Written a Legend(Codeforces Round #546 (Div. 2)E+线段树)

    题目链接 传送门 题面 题意 给你一个\(a\)数组和一个\(k\)数组,进行\(q\)次操作,操作分为两种: 将\(a_i\)增加\(x\),此时如果\(a_{i+1}<a_i+k_i\),那 ...

  2. 微信小程序~TabBar底部导航切换栏

    底部导航栏这个功能是非常常见的一个功能,基本上一个完成的app,都会存在一个导航栏,那么微信小程序的导航栏该怎么实现呢?经过无数的踩坑,终于实现了,好了,先看看效果图. 对于底部导航栏,小程序上给出的 ...

  3. 《The One 团队》:第九次团队作业:BETA冲刺与团队项目验收

    项目 内容 作业所属课程 所属课程 作业要求 作业要求 团队名称 < The One !> 作业学习目标 (1)掌握软件黑盒测试技术:(2)学会编制软件项目总结PPT.项目验收报告:(3) ...

  4. Unity点击播放卡死问题的解决

    Unity项目使用了github for unity 插件,用来管理项目,结果安装完后Unity卡死在播放的界面,任务管理器中显示无响应. 经过排查后发现是 git for windows这个程序引起 ...

  5. python面试题&练习题之运算符与if控制

    1.任意的输入10个数字,按从大到小排序 l2 = [] for i in range(1,11): num = input('输入第{}个数字'.format(i)) if num.isdigit( ...

  6. web自动化测试-自动化测试模型介绍

    一.线性测试 什么是线性测试? 通过录制或编写对应用程序的操作步骤产生相应的线性脚本,每个测试脚本相对独立,不产生依赖和调用,单纯的来模拟用户完整的操作场景 缺点 1.开发成本高,测试用例之间存在重复 ...

  7. Access数据库连接封装类

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  8. 自定义注解-aop实现日志记录

    关于注解,平时接触的可不少,像是 @Controller.@Service.@Autowried 等等,不知道你是否有过这种疑惑,使用 @Service 注解的类成为我们的业务类,使用 @Contro ...

  9. .net core 多sdk 多版本 环境切换

    在讲述.net core多版本之前,我们先理解一下.net core sdk与.net core runtime之前的联系与区别,根据官网的解释我们可以简单地理解为:sdk是在开发过程中进行使用,而r ...

  10. 计蒜客 39268.Tasks-签到 (The 2019 ACM-ICPC China Shannxi Provincial Programming Contest A.) 2019ICPC西安邀请赛现场赛重现赛

    Tasks It's too late now, but you still have too much work to do. There are nn tasks on your list. Th ...