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. 前端工程师应该都了解的16个最受欢迎的CSS框架

    摘要: 今天给大家分享16个最受欢迎的CSS框架.这些是根据笔者的爱好以及相关查阅规整出来的.可能还有一些更棒的或者您更喜欢的没有列举出来.如果有,欢迎留言! Pure : CSS Framework ...

  2. Windows下用VC与QT编译MPI程序入门

    MPI是信息传递接口的简称,常用来进行进程间.机器间的通信与并行计算.一般而言,MPI都会部署在*nix系统下,在Windows下面直接编译.配置MPI并不容易.本文利用MS提供的编译好的MPI的版本 ...

  3. Qt之QGraphicsEffect阴影、模糊效果

    Qt之QGraphicsEffect阴影.模糊效果 Qt之QGraphicsEffect阴影模糊效果 效果图 阴影和模糊效果 正常效果 代码 customshadoweffecth customsha ...

  4. xmanager小技巧

    使用manager时候,左键选中之后,直接右键粘贴,能带来效率的提升.虽然是小技巧,但有人还是不知道,这里简单写一下,供需要的同学参考. 简单二步设置: 1.工具-选项

  5. 【数据结构】30、hashmap=》hash 计算方式

    前提知识 写在前面,为什么num&(length - 1) 在length是2的n次幂的时候等价于num%length n - 1意味着比n最高位小的位都为1,而高的位都为0,因此通过与可以剔 ...

  6. java关键字之synchronized

    1.synchronized可以用了修饰一个普通方法,或者代码块,这个时候synchronized锁定的是当前对象,只要有一个线程在访问对应的方法或代码块,其他线程必须等待.2.synchronize ...

  7. Centos 7上安装Python3.x(单版本)

    Centos7默认安装的是2.7,这里选择安装使用Python3.6.3 安装Python3.6.3 1.安装python3 需要的依赖包 yum install -y openssl-devel b ...

  8. python面试题(-)可变数据类型与不可变数据类型

    python3中有六个标准的数据类型:number(数字型).string(字符串型).list(列表).type(元祖).dictionary(字典).set(集合),其中不可变类型三个:numbe ...

  9. .NET开发框架(五)-IIS上部署ASP.NET Core项目教程

    系列教程:从初学者到架构师的一步步蜕变 本篇经验将和大家介绍如何在IIS上部署ASP.NET Core项目,希望对初学.NET CORE的童靴入门有所帮助! 1.打开VS,创建项目,选择ASP.NET ...

  10. 找不到 main 方法

    前几天打开了好久不用的eclipse,发现报了个奇怪的错误 ***中找不到 main 方法, 请将 main 方法定义为: public static void main(String[] args) ...