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. 中国自主X86处理器工艺跃进:国产28nm升级16nm(上海兆芯)

    提到X86处理器,世人皆知Intel.AMD,殊不知还有个VIA(威盛),在Intel反垄断世纪大战中VIA公司作为Intel霸权的受害者也最终确认了X86授权,不过VIA与前面两家的实力相差太远,X ...

  2. EF CodeFirst数据迁移与防数据库删除

    1 开启migrations功能 enable-migrations -force 2 添加迁移版本 add-migration 名称后缀 我们每次修改实体后,都应该使用这个add-migration ...

  3. webform的图片防盗链

    最近用到域的问题,不是同一主机的请求将不允许请求此页面. 这其实和图片防盗链的本质是一样的. 通过两个属性:由于当时用的aspx视图引擎,所以需要通过HttpContext.Current才能拿到ht ...

  4. linux下编译qt5.6.0静态库(使用./configure --help来看看都有哪些参数。超详细,有每一个模块的说明。如果改变了安装的目录,需要到安装目录下的bin目录下创建文件qt.conf)(乌合之众)good

    linux下编译qt5.6.0静态库 linux下编译qt5.6.0静态库 configure生成makefile 安装选项 Configure选项 第三方库: 附加选项: QNX/Blackberr ...

  5. c# 9png实现(图片缩放)

    跟据9png的实现原理自己写了个生成图片的函数,9png的原理是将图片切成9块如下 其中1.3.7.9不进行缩放,2,4,5,6,8进行缩放,这样就防止了放大后导致边界出现锯齿的问题 在实现过程中主要 ...

  6. QT---Native Wifi functions 应用(WiFi有密码连接)

    实现功能     无线网卡列表     无线热点扫面     无线连接(有密码,配置文件连接方式)     无线断开     重命名本地无线名(两种方式)     删除无线配置文件     开启和关闭 ...

  7. SYN3305A型 小型时统设备

       SYN3305A型  小型时统设备 产品概述 SYN3305A型小型时统设备是由西安同步电子科技有限公司精心设计.自行研发生产的一款高准确度的锁相石英频率标准.内装OCX0恒温晶体振荡器,利用G ...

  8. Hexo+NexT(三):Next主题配置详解

    阅读本篇之前,假定读者已经有了Node.js的基础,如需要补充Node.js知识的,请自行百度. Hexo是在Node.js框架下的一个项目,利用Node.js提供的强大功能,完成从Markdown到 ...

  9. 【Mysql】细节补充,约束、索引等

    约束: 显示建表语句:show create table 表名 查询表中的约束:SELECT * FROM information_schema.`TABLE_CONSTRAINTS`  where ...

  10. 【设计模式】行为型01策略模式(strategy patten)

    学设计模式一段时间了,有些懂了,有些半知半解,通过写笔记博客的方式总结一下: 关于策略模式,我的个人理解就是将一些经常变动的算法独立抽取出来,可以是一个方法,也可以是一个策略类,这样,如果有需求变更, ...