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. 【JS 笔记】比较操作符之大小与记录

    1,字符串比较 字符串比较则是使用基于标准字典的 Unicode 值来进行比较的. 对于两个拥有相同字符顺序,相同长度,并且每个字符的位置都匹配的字符串,应该使用严格比较运算符. 下例的比较中可能因为 ...

  2. WCSTOMBS 函数不支持中文件的解决方法(设置代码页)

    代码页没有进行设置.需要调用locale.h 中定义的一个函数设置默认的代码页 _tsetlocale(LC_ALL,_T(""));//设置代码页  wcstombs(sendB ...

  3. 使用 acl 编写 UDP 网络程序(UDP 重传及可靠性机制)

    在当今网络世界,虽然大部分网络应用都是基于 TCP 的,但有时 UDP 的网络通信也有用武之处.acl 的网络库中不仅提供了基于 TCP 的网络套接字流,同时也提供了 UDP 的网络库(目前 acl ...

  4. java集合框架collection(4)HashMap和Hashtable的区别

    HashMap和Hashtable的区别 HashMap和Hashtable都实现了Map接口,但决定用哪一个之前先要弄清楚它们之间的分别.主要的区别有:线程安全性,同步(synchronizatio ...

  5. Mac上使用brew安装nvm来支持多版本的Nodejs

    brew方式 如果机器没有安装过node,那么首先brew install nvm安装nvm. 其次需要在shell的配置文件(~/.bashrc, ~/.profile, or ~/.zshrc)中 ...

  6. 你一定能看懂的JDK动态代理

    前言:阅读这篇文章前,一定要知道什么是代理模式,具体可以参考这篇文章<设计模式(一):代理模式>. 在<设计模式(一):代理模式>一文中说了,程序员思思买书有两种选择:一种是选 ...

  7. ios开发系列之内存泄漏分析(上)

    ios自从引入ARC机制后,一般的内存管理就可以不用我们码农来负责了,但是一些操作如果不注意,还是会引起内存泄漏. 本文主要介绍一下内存泄漏的原理.常规的检测方法以及出现的常用场景和修改方法. 1.  ...

  8. React躬行记(5)——React和DOM

    React实现了一套与浏览器无关的DOM系统,包括元素渲染.节点查询.事件处理等机制. 一.ReactDOM 自React v0.14开始,官方将与DOM相关的操作从React中剥离,组成单独的rea ...

  9. 【转】三次握手——https为什么更安全

    三次握手与四次挥手: https://blog.csdn.net/legend050709/article/details/39804519 https://blog.csdn.net/luoyoub ...

  10. 牛客假日团队赛1 B

    B.便便传送门(一) 题目链接:https://ac.nowcoder.com/acm/contest/918/B 题目 Farmer John最讨厌的农活是运输牛粪.为了精简这个过程,他制造了一个伟 ...