Baozi Leetcode Solution 290: Word Pattern
Problem Statement
pattern and a string str, find if str follows the same pattern.pattern and a non-empty word in str.Input: pattern ="abba", str ="dog cat cat dog"
Output: true
Input:pattern ="abba", str ="dog cat cat fish"
Output: false
Input: pattern ="aaaa", str ="dog cat cat dog"
Output: false
Input: pattern ="abba", str ="dog dog dog dog"
Output: false
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
Baozi Leetcode Solution 290: Word Pattern的更多相关文章
- 【leetcode】290. Word Pattern
problem 290. Word Pattern 多理解理解题意!!! 不过博主还是不理解,应该比较的是单词的首字母和pattern的顺序是否一致.疑惑!知道的可以分享一下下哈- 之前理解有误,应该 ...
- Leetcode solution 291: Word Pattern II
Problem Statement Given a pattern and a string str, find if str follows the same pattern. Here follo ...
- 【一天一道LeetCode】#290. Word Pattern
一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...
- 【LeetCode】290. Word Pattern 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- leetcode 290. Word Pattern 、lintcode 829. Word Pattern II
290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...
- leetcode面试准备: Word Pattern
leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...
- [LeetCode] 290. Word Pattern 词语模式
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
- LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)
翻译 给定一个模式,和一个字符串str.返回str是否符合同样的模式. 这里的符合意味着全然的匹配,所以这是一个一对多的映射,在pattern中是一个字母.在str中是一个为空的单词. 比如: pat ...
- [LeetCode] 290. Word Pattern 单词模式
Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...
随机推荐
- EF 里的 join and Group Join
join ); pageCount = _db.Orders.Count(); return _db.Orders.OrderByDescending(c=>c.ID).Skip(skip).T ...
- SharePoint Add-in Model 介绍 - 引文(先导篇)
1. SharePoint 平台 如果你已经很熟悉 SharePoint 平台,可跳过本章节. 1.1 SharePoint 是什么 在介绍 Add-in Model 之前,简要提一下 SharePo ...
- RapidJSON 1.0 正式版发布,C++的JSON开发包
分享 <关于我> 分享 [中文纪录片]互联网时代 http://pan.baidu.com/s/1qWkJfcS 分享 <HTML开发MacOSAp ...
- 2015新款 MacBook 用心的测评与试用. 最轻薄的Mac上市
2015新款 MacBook 不一样的测评与试用. 最轻薄的Mac上市了. 直击现场 <HTML开发MacOSApp教程> http://pan.baidu.com/s/1jG1Q58M ...
- QT+OpenGL读取显示图片,OpenGL在QT里的刷新问题(好几篇)
GLuint readImage(char *filename){ GLuint tex_id; GLint alignment; QImage tex, buf; buf.load ...
- C语言程序的内存布局
C语言程序的内存布局 一:C语言程序的存储区域 C语言编写的程序经过编绎-链接后,将形成一个统一的文件,它由几个部分组成,在程序运行时又会产生几个其他部分,各个部分代表了不同的存储区域: 1.代码段( ...
- vista下开机启动 简单绕过UAC的方法(自己使用runas参数重新启动自己,有点意思)
背景 vista下,如果不开启UAC,那就没有我下面要说的问题了,呵呵.下面说的都是在vista开启UAC的前提下说的,win7也适用. 在vista下,系统开启了UAC,如果你的 ...
- Gradle添加外部项目代码
为了测试一些功能,我想在公司的项目中引进外部项目的子模块代码进来调试,试验了好半天终于成功了... 原来不需要导入代码,只要在settings.gradle中这样就好了: 然后就可以和原项目中的代码一 ...
- Centos7安装Mysql-最方便、最快捷
你想在Linux操作系统安装Mysql?你不想去官网下载再复制?,那就来看看我的方案,简单.快捷轻松安装.使用. 首先,检查安装情况 1.查看有没有安装过: yum ...
- Linux上整数和浮点数的运算
一:shell中对整数和浮点数的运算 常用的运算符号 加法+ 减法 - 乘法* 除法/ 求余% += -= ...
