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 ...
随机推荐
- C# ACCESS 查询提示“至少一个参数没有被指定”问题
错误的SQL指令如下: sqlStr = “select * from tb_userInfo where userName=” + userName; //错误的 sql 指令 正确的SQL ...
- c#透明TextBox
在 http://www.codeproject.com/KB/edit/AlphaBlendedTextControls.aspx 的基础上增加了水印文字 代码如下: public class Te ...
- Windows下获取高精度时间注意事项 [转贴 AdamWu]
花了很长时间才得到的经验,与大家分享. 1. RDTSC - 粒度: 纳秒级 不推荐优势: 几乎是能够获得最细粒度的计数器抛弃理由: A) 定义模糊 - 曾经据说是处理器的cycle counter, ...
- C# 对字段忽略模型校验
1.在if (!ModelState.IsValid)之前给字段赋值,然后TryUpdateModel()2.使用如下方法 public ActionResult Create([Bind(Exclu ...
- 多进程demo
多进程实现DOS重定向输出,界面如下: 主要的代码实现如下: #define MAXREADBUFFERLEN (60 * 1000) void CRedirectDlg::OnBnClickedBu ...
- spring boot单元测试之RestTemplate(一)
写代码重要,写好的代码准确无误,且符合预期那更是必不可少. spring boot内嵌了专门的单元测试模块——RestTemplate,保证了程序员可以对自己的代码进行及时的测试. 闲言少叙,直接上代 ...
- java中的String、StringBuffer、StringBuilder的区别
java中String.StringBuffer.StringBuilder是编程中经常使用的字符串类,他们之间的区别也是经常在面试中会问到的问题.现在总结一下,看看他们的不同与相同. 1.可变与不可 ...
- 第一个SpringBoot测试实例
1.SpringBoot项目构建:http://start-spring.io 自动化构建SpringBoot项目,保存在本地并解压 2.安装gradle并配置gradle环境 3.配置阿里云ma ...
- 移动IM开发指南3:如何优化登录模块
<移动IM开发指南>系列文章将会介绍一个IM APP的方方面面,包括技术选型.登陆优化等.此外,本文作者会结合他在网易云信多年iOS IM SDK开发的经验,深度分析实际开发中的各种常见问 ...
- Java学习笔记——MySQL创建表结构
一.创建/删除数据库. create database t14; drop database t14; use t14; 二.创建若干表用于测试 这里预留了几个坑,下面要填坑的.. /*创建学生表*/ ...