Leetcode solution 291: Word Pattern II
Problem Statement
pattern and a string str, find if str follows the same pattern.pattern and a non-empty substring in str.Input: pattern ="abab", str ="redblueredblue"
Output: true
Input: pattern = pattern ="aaaa", str ="asdasdasdasd"
Output: true
Input: pattern ="aabb", str ="xyzabcxzyabc"
Output: false
You may assume both
pattern and str contains only lowercase letters.Problem link
Video Tutorial
You can find the detailed video tutorial here
- Youtube
- B站
Thought Process
It is quite similar to Word Pattern and Isomorphic String problem, where we would keep a mapping from char to a string while also ensure there would be a one to one mapping, i.e., bijection mapping. The tricky part is it seems there are way many combinations of the mapping, how can we efficiently solve them?
Maybe we could list all the combinations? Maybe we could use DP since it is string related and only ask for true/false result?
How to list all combinations? Think about this way, let's say you have pattern = "aba" and str = "redbluered", since one char in pattern can map to any string length >= 1 in str, it is equivalent to divide up str into 3 parts (length of pattern) and check all cases. For instance, the cut of the words is like below:
- r | e | d b l u e r e d
- r | e d | b l u e r e d
- r | e d b | l u e r e d
- r | e d b l | u e r e d
- r | e d b l u | e r e d
- r | e d b l u e | r e d
- r | e d b l u e r | e d
- r | e d b l u e r e | d
- r e | d | b l u e r e d
- r e | d b | l u e r e d
- r e | d b l | u e r e d
- r e | d b l u | e r e d
- r e | d b l u e | r e d
- r e | d b l u e r | e d
- r e | d b l u e r e | d
- r e d | b | l u e r e d
- .....
In general, if the length of pattern is M, the str length is N, the time complexity of this brute force method is O(N^M), more accurately, it should be

DP solution does not work since we cannot easily get a deduction formula :(
Solutions
Brute force list all the combos
For each character in pattern, try to map any possible remaining strings in str from length 1 to the end. During this process, need to make sure the string mapping is bijection (no two chars in pattern map to the same string in str) and if a mapping has been seen before, continue use that mapping
A DFS recursion would be the implementation. A few caveats in implementation
- Remember to reset the map and set after recursion returned false
- When there is a bijection mapping, should continue instead of directly break
public boolean wordPatternMatch(String pattern, String str) {
if (pattern == null || str == null) {
return false;
}
Map<Character, String> lookup = new HashMap<>();
Set<String> dup = new HashSet<>();
return this.isMatch(pattern, str, lookup, dup);
}
// DFS recursion to list out all the possibilities
public boolean isMatch(String pattern, String str, Map<Character, String> lookup, Set<String> dup) {
if (pattern.length() == 0) {
return str.length() == 0;
}
char c = pattern.charAt(0);
if (lookup.containsKey(c)) {
String mappedString = lookup.get(c);
if (mappedString.length() > str.length()) {
return false;
}
// could use str.startsWith(mappedString)
if (!mappedString.equals(str.substring(0, mappedString.length()))) {
return false;
}
return this.isMatch(pattern.substring(1), str.substring(mappedString.length()), lookup, dup);
} else {
for (int i = 1; i <= str.length(); i++) {
String mappingString = str.substring(0, i);
if (dup.contains(mappingString)) {
// not a bijection mapping, not not return false, but continue
continue;
}
lookup.put(c, mappingString);
dup.add(mappingString);
if (this.isMatch(pattern.substring(1), str.substring(i), lookup, dup)) {
return true;
}
// reset value for next recursion iteration for backtracking
lookup.remove(c);
dup.remove(mappingString);
}
}
return false;
}
Time Complexity: O(N^M), or C(N^M) to be exact. Pattern length is M, str length is N
Space Complexity: O(M), Pattern length is M, str length is N. We use a map and a set to store the lookup, but at one time, the map should not exceed the pattern size, so is the set
References
Leetcode solution 291: Word Pattern II的更多相关文章
- [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 mat ...
- 291. Word Pattern II
题目: Given a pattern and a string str, find if str follows the same pattern. Here follow means a full ...
- Baozi Leetcode Solution 290: Word Pattern
Problem Statement Given a pattern and a string str, find if str follows the same pattern. Here follo ...
- leetcode 290. Word Pattern 、lintcode 829. Word Pattern II
290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...
- Word Pattern | & II
Word Pattern | Given a pattern and a string str, find if str follows the same pattern. Examples: pat ...
- Word Pattern II 解答
Question Given a pattern and a string str, find if str follows the same pattern. Here follow means a ...
- leetcode面试准备: Word Pattern
leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...
- [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 OJ】Word Break II
Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...
随机推荐
- 修改用户名后TSF出现"需要本地工作区。工作区 xxx 并未驻留在本计算机上"
解决方法就是:1,打开vs下的"开发人员命令提示"2,按下面格式输入命令:tf workspaces /collection:http://192.168.0.110:8080/t ...
- ML:单变量线性回归(Linear Regression With One Variable)
模型表达(model regression) 用于描述回归问题的标记 m 训练集(training set)中实例的数量 x 特征/输入变量 y 目标变量/输出变量 (x,y) 训练集中的实例 (x( ...
- Windows下搭建go语言开发环境 以及 开发IDE (附下载链接)
1.下载 并且 安装 Go安装包 =========================================================== 在CSDN上传了我的版本,供大家下载: = ...
- SYN5605型 多通道时间间隔测量仪
SYN5605型 多通道时间间隔测量仪 时间间隔测量设备多通道时间间隔测量32路时间间隔测量仪使用说明视频链接; http://www.syn029.com/h-pd-80-0_310_6_-1. ...
- SYN2101型 NTP网络时间服务器
SYN2101型 NTP网络时间服务器 时钟校准服务器时间 ntp服务器ntp时间校准服务器使用说明视频链接: http://www.syn029.com/h-pd-56-0_310_1_-1. ...
- 【JavaScript】彻底明白this在函数中的指向
一.this,其实可以类比成人 说到this的话,我们在js中主要研究的都是函数中的this,在javascript中,this代表当前行为的执行主体,而context代表的是当前行为执行的的环境(区 ...
- Kali Linux Web渗透测试手册(第二版) - 1.1 - Firefox浏览器下安装一些常用的插件
一.配置KALI Linux和渗透测试环境 在这一章,我们将覆盖以下内容: l 在Windows和Linux上安装VirtualBox l 创建一个Kali Linux虚拟机 l 更新和升级Ka ...
- raft算法解析
一.raft算法引入 在寻找一种易于理解的一致性算法的研究(In Search of an Understandable Consensus Algorithm-extended version) 论 ...
- .Net之使用Jquery Ajax通过FormData对象异步提交图片文件到服务端保存并返回保存的图片路径
前言: 首先对于图片上传而言,在我们的项目开发中可以说出现的频率是相当的高的.这篇文章中,我将要描述的是在我们.Net中如何使用Jquery Ajax通过FormData对象异步提交图片文件到后台保存 ...
- K8s集群部署(二)------ Master节点部署
Master节点要部署三个服务:API Server.Scheduler.Controller Manager. apiserver提供集群管理的REST API接口,包括认证授权.数据校验以 及集群 ...