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 ...
随机推荐
- QQ邮箱打败163邮箱的过程(重视用户体验的结果)
引用 楼主 CKAOS 的回复: 目前负责一个项目,ASP.NET的,做一个网盘系统,别的都弄好了,只差一个下载文件夹的功能未实现,只能在服务器端打包成压缩文件,再发回浏览器.如何直接下载文件夹,不是 ...
- Tomcat cache 缓存 编译
http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html development - Is Jasper used in developmen ...
- <房间内功能>打赏小动画
截图如下 : 功能: 每次点击礼物,都要通过动画显示一个小图标,最多显示两行图标栏,送多次会显示然后再次显示,显示 XX 送给 XX 一个小礼物的动画样式.动画样式效果为,整体动画模 ...
- <iOS小技巧> 返回上级目录操作Goback()方法
Goback()方法功能:返回上一级界面,通过判断 popViewControllerAnimated 类型是否为空,来判断是present还是pop出来,然后直接做了releaseSelf操作: - ...
- Google C++测试框架系列入门篇:第一章 介绍:为什么使用GTest?
原始链接:Introduction: Why Google C++ Testing Framework? 词汇表 版本号:v_0.1 介绍:为什么使用GTest? GTest帮助你写更好的C++测试代 ...
- 《C++ Primer》读书笔记 第三章
1.注意:头文件不应包含using声明.因为头文件的内容会拷贝到所有引用他的文件中去,对于某些程序来说,由于不经意间包含了一些名字,可能会产生名字冲突.2.string类型的读入:用cin读入stri ...
- Hadoop集群(第1期)CentOS安装配置
1.准备安装 1.1 系统简介 CentOS 是什么? CentOS是一个基于Red Hat 企业级 Linux 提供的可自由使用的源代码企业级的 Linux 发行版本.每个版本的 CentOS 都会 ...
- Postman支持的几种数据类型请求方式
一.postman作为web应用开发工具,可以用于模拟多种请求方式,但是支持的传参类型又不尽相同.根据面板上的几种数据打包方式来选择合适的请求数据类型. form-data 就是http请求中的mul ...
- memcached--delete--replace--set--get--incr--decr--stats
memcached命令 1.get key 来获取在内存中的值 get name 2.delete key 删除在内存中的值 delete name 3.replace key flag exp ...
- ELK架构下利用Kafka Group实现Logstash的高可用
系统运维的过程中,每一个细节都值得我们关注 下图为我们的基本日志处理架构 所有日志由Rsyslog或者Filebeat收集,然后传输给Kafka,Logstash作为Consumer消费Kafka里边 ...