Problem Statement

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.
Example 1:
Input: pattern = "abab", str = "redblueredblue"
Output: true
Example 2:
Input: pattern = pattern = "aaaa", str = "asdasdasdasd"
Output: true
Example 3:
Input: pattern = "aabb", str = "xyzabcxzyabc"
Output: false
Notes:
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:

  1. r | e | d b l u e r e d
  2. r | e d | b l u e r e d
  3. r | e d b | l u e r e d
  4. r | e d b l | u e r e d
  5. r | e d b l u | e r e d
  6. r | e d b l u e | r e d
  7. r | e d b l u e r | e d
  8. r | e d b l u e r e | d
  9. r e | d | b l u e r e d
  10. r e | d b | l u e r e d
  11. r e | d b l | u e r e d
  12. r e | d b l u | e r e d
  13. r e | d b l u e | r e d
  14. r e | d b l u e r | e d
  15. r e | d b l u e r e | d
  16. r e d | b | l u e r e d
  17. .....

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的更多相关文章

  1. [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 ...

  2. 291. Word Pattern II

    题目: Given a pattern and a string str, find if str follows the same pattern. Here follow means a full ...

  3. Baozi Leetcode Solution 290: Word Pattern

    Problem Statement Given a pattern and a string str, find if str follows the same pattern. Here follo ...

  4. leetcode 290. Word Pattern 、lintcode 829. Word Pattern II

    290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...

  5. Word Pattern | & II

    Word Pattern | Given a pattern and a string str, find if str follows the same pattern. Examples: pat ...

  6. Word Pattern II 解答

    Question Given a pattern and a string str, find if str follows the same pattern. Here follow means a ...

  7. leetcode面试准备: Word Pattern

    leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...

  8. [LeetCode] Word Pattern II 词语模式之二

    Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

  9. 【LeetCode OJ】Word Break II

    Problem link: http://oj.leetcode.com/problems/word-break-ii/ This problem is some extension of the w ...

随机推荐

  1. 无法解决 equal to 操作中 "SQL_Latin1_General_CP1_CI_AS" 和 "Chinese_PRC_CI_AS" 之间的排序规则冲突。

    无法解决 equal to 操作中 "SQL_Latin1_General_CP1_CI_AS" 和 "Chinese_PRC_CI_AS" 之间的排序规则冲突 ...

  2. 简析TCP的三次握手与四次分手(TCP协议头部的格式,数据从应用层发下来,会在每一层都会加上头部信息,进行封装,然后再发送到数据接收端)good

    2014-10-30 分类:理论基础 / 网络开发 阅读(4127) 评论(29)  TCP是什么? 具体的关于TCP是什么,我不打算详细的说了:当你看到这篇文章时,我想你也知道TCP的概念了,想要更 ...

  3. CentOS 如何删除/delete/remove 老的 kernel

    package-cleanup --oldkernels --count=1

  4. 留存: struts2+jquery+json集成

    原文地址:struts2+jquery+json集成 以下采用struts2+jquery+json模拟一个案例.当点击提交按钮时会把输入的数据提交到后台,然后从后台获取数据在客户端显示. 效果如下: ...

  5. Dynamics 365 Document Management

    Dynamics CRM中的Document Management功能需要Dynamics CRM与SharePoint进行集成,也就是实现在CRM中上传Document,实际上Document最终存 ...

  6. 627.Swap Salary-(LeetCode之Database篇)

    问题描述 给出下面的表,名为salary. id name sex salary 1 A m 2500 2 B f 1500 3 C m 5500 4 D f 500 要求执行一个UPDATE语句,将 ...

  7. 【转】Linux下添加FTP账号和服务器、增加密码和用户,更改FTP目录

    转自:http://blog.csdn.net/cloudday/article/details/8640234   1. 启动VSFTP服务器 A:cenos下运行:yum  install  vs ...

  8. Python 爬虫从入门到进阶之路(八)

    在之前的文章中我们介绍了一下 requests 模块,今天我们再来看一下 Python 爬虫中的正则表达的使用和 re 模块. 实际上爬虫一共就四个主要步骤: 明确目标 (要知道你准备在哪个范围或者网 ...

  9. 如何用 Flutter 实现混合开发?闲鱼公开源代码实例

    Flutter: 必火,转两篇软文预热哈哈~ 中文网: https://flutterchina.club/get-started/test-drive/ 如何用 Flutter 实现混合开发?闲鱼公 ...

  10. php7中异常

    php7中新增异常错误处理 在PHP7之前的版本,对于一些错误异常是没有办法捕获的. php7中新增throwable接口,可以用来捕获一些错误 Exception,Error这实现了Throwabl ...