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 word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.

Problem link

Video Tutorial

You can find the detailed video tutorial here

Thought Process

A very simple problem thus normally can solve it in multiple ways.

Encode string and patterns then compare

Since we are comparing "patterns" here, one straightforward way is encode the pattern into a string, then use the same encoding algorithm to encode the str array into a string, then compare the string.

What encoding should we choose? Well it's not really an encoding per se. What I did is just convert any word or character to a character staring with ('a' + an index). If we see this character before, we just directly return from the hash map lookup. For example, "duck dog dog" would be encoded as "abb" while "bcc" would also be encoded as "abb".

Use bijection mapping

Note in the problem description it mentions it is a bijection mapping (i.e., a one to one mapping).
As shown in the graph below, you see the differences between injection, surjection and bijection. That said, bijection does not allow duplicates. We can build a one to one mapping between the pattern and string, since it's bijection, if two characters in the pattern map to the same string, then it's not a valid bijection, therefore return false.

Ref: https://en.wikipedia.org/wiki/Injective_function
 

Solutions

Encode string and patterns then compare

  // This way will also work, just a little bit more work by encoding each string into the same one
// Kinda similar to the isomorphic string
public boolean wordPatternEncoding(String pattern, String str) {
if (str == null || str.isEmpty() || pattern == null || pattern.isEmpty()) {
return false;
} String[] s = str.split(" ");
if (pattern.length() != s.length) {
return false;
} // encode pattern
String patternEncoded = this.encodeString(pattern);
// encode the string array
String strEncoded = this.encodeArray(s); // compare
return patternEncoded.equals(strEncoded);
} private String encodeArray(String[] s) {
Map<String, Character> lookup = new HashMap<>(); int index = 0; // starting from 'a'
StringBuilder sb = new StringBuilder();
for (String ss : s) {
if (lookup.containsKey(ss)) {
sb.append(lookup.get(ss));
} else {
char c = (char)('a' + index);
sb.append(c);
index++;
lookup.put(ss, c);
}
}
return sb.toString();
} // encode it to base to a, this is not really encoding, but mapping a char to a completely different one using
// the same order as encodeArray
private String encodeString(String s) {
Map<Character, Character> lookup = new HashMap<>();
int index = 0; // starting from 'a'
StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); if (lookup.containsKey(c)) {
sb.append(lookup.get(c));
} else {
char t = (char)('a' + index);
sb.append(t);
index++;
lookup.put(c, t);
}
} return sb.toString();
}

Time Complexity: O(N), N is the length of pattern or string array, we loop it 3 times, but still O(N)
Space Complexity: O(N), N is the length of pattern or string array, we need the extra map and string to store the results

Use bijection mapping (Recommended)

 // I recommend this solution: just need map to keep the mapping relationship
public boolean wordPattern(String pattern, String str) {
if (pattern == null || pattern.length() == 0 || str == null || str.length() == 0) {
return false;
} String[] strs = str.trim().split(" "); if (pattern.length() != strs.length) {
return false;
} Map<Character, String> lookup = new HashMap<>();
// As it says, it is a bijection, so it needs to be 1 to 1 mapping, cannot exist a case one key maps to different value case
// E.g., need this set for abba, dog dog dog dog -> false case
Set<String> mapped = new HashSet<>(); for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i); if (lookup.containsKey(c)) {
if (!lookup.get(c).equals(strs[i])) {
return false;
}
} else {
// shit, just know put actually returns a V, which is the previous value, or null if not exist (or an associated null value)
lookup.put(c, strs[i]);
if (mapped.contains(strs[i])) {
return false;
}
mapped.add(strs[i]);
}
} return true;
}

There is also a clever implementation like below. The key point is use the index to compare, if there is duplicate index, meaning there are two keys already mapped to the same value. Also, remember java put() returns a valid, not a void :)

 // Reference: https://leetcode.com/problems/word-pattern/discuss/73402/8-lines-simple-Java
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}

Time Complexity: N is the length of pattern or string array
Space Complexity: O(N), N is the length of pattern or string array, we need a map regardless

References

最新文章

  1. 解析sql语句中left_join、inner_join中的on与where的区别
  2. 动态平衡二叉搜索树的简易实现,Treap 树
  3. codeforces 711B B. Chris and Magic Square(水题)
  4. 对原型prototype的详解
  5. Socket 两平台互相 通信 .NET
  6. 结构体定义 typedef struct 用法详解和用法小结
  7. jquery选择器之层级过滤选择器
  8. web前端 ajax请求上传图片数据类型处理
  9. 深蓝词库转换2.4版发布,支持最新的搜狗用户词库备份bin格式
  10. MySQL导入数据报 Got a packet bigger than‘max_allowed_packet’bytes 错误的解决方法
  11. Vue Resource root options not used?
  12. CIFAR-10数据集读取
  13. Kettle从excel导入数据到sql server
  14. 利用sed把一行的文本文件改成每句一行
  15. 20145313张雪纯exp7
  16. 第九章 对称加密算法--IDEA
  17. MongoDB Python官方驱动 PyMongo 的简单封装
  18. BZOJ 4726 POI 2017 Sabota? 树形DP
  19. 利用层的table-row、table-cell属性进行页面布局
  20. 简单的Slony-I设置实例 II

热门文章

  1. Qt-vs-addin失效的问题
  2. 网络文件系统nfs文件系统使用(很全面)
  3. SYN2306型 北斗串口时间服务器
  4. SYN2306A型 GPS北斗双模授时板
  5. python文件及路径管理函数
  6. Adboe Flash远程代码执行_CVE-2018-4878漏洞复现
  7. SpringBoot项目多数据源配置
  8. chmod命令用法详解-chmod修改目录权限
  9. 【HDU - 1010】Tempter of the Bone(dfs+剪枝)
  10. python的自定义函数