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 ...
随机推荐
- 判断jQuery选择器结果为空 - CSDN博客
原文:判断jQuery选择器结果为空 - CSDN博客 jQuery选择器获取到的是一个对象,所以无论页面上存在或者不存在元素,这个对象都不为空.因此,如果要使用jQuery检查元素再给某个页面上是否 ...
- Qt5---ftp上传功能(可直接克隆某个小模块,查看QT下FTP的socket原理)
http://blog.csdn.net/freeape/article/details/52802163
- SQLite实现内存键值存储
SQLite数据文件往Linux内存文件系统/dev/shm/data.sqlite3一放,就是内存级读写性能的SQL系统.用SQLite实现内存键值存储:CREATE TABLE IF NOT EX ...
- 在mac上尝试docker-swarm
声明:本博客欢迎转发,但请保留原作者信息!新浪微博:@Lingxian_kong;博客地址:孔令贤的博客;内容系本人学习.研究和总结,如有雷同,实属荣幸! 安装docker-machine 我的安装环 ...
- FastDFS结合FastDHT实现文件去重存储
存储文件时,为了节省存储空间,需要实现文件去重,即同一份文件只在服务器上存储一份.一种实现是文件上传后先落到应用服务器上,计算MD5并存储到数据库中,然后决定是否上传存储服务器.这样做的缺点是应用服务 ...
- 【Linux】linux中删除指定日期之前的文件
要删除系统中就的备份文件,就需要使用命令了: #find /tmp -mtime +30 -type f -name *.sh[ab] -exec rm -f {} \; 假如在一个目录中保留最近30 ...
- Windows服务器下的IIS和Apache性能比较
目前最流行的建立网站的服务工具就要属Apache与IIS了.那么他们之间到底哪个性能更好呢?到底哪个工具才是最适合我们的呢?最近我也对这方面的问题进行了一番研究. 如果是基于Linux平台的话,那不必 ...
- 机器学习经典算法之KNN
一.前言 KNN 的英文叫 K-Nearest Neighbor,应该算是数据挖掘算法中最简单的一种. 先用一个例子体会下. /*请尊重作者劳动成果,转载请标明原文链接:*/ /* https://w ...
- 最全java多线程总结2--如何进行线程同步
上篇对线程的一些基础知识做了总结,本篇来对多线程编程中最重要,也是最麻烦的一个部分--同步,来做个总结. 创建线程并不难,难的是如何让多个线程能够良好的协作运行,大部分需要多线程处理的事情都不 ...
- C语言-main方法的两个参数是干什么的?
大家都知道C语言的main方法怎么写的吧!但你们知道mian方法里的参数的含义吗? 代码如下: int main(int argc,char *argv[]){ //argc是传进的参数个数 //ar ...