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`.

Examples:

1. pattern = `"abba"`, str = `"dog cat cat dog"` should return true.
2. pattern = `"abba"`, str = `"dog cat cat fish"` should return false.
3. pattern = `"aaaa"`, str = `"dog cat cat dog"` should return false.
4. pattern = `"abba"`, str = `"dog dog dog dog"` should return false.

Notes:
You may assume `pattern` contains only lowercase letters, and `str` contains lowercase letters separated by a single space.

Time Complexity- O(n)， Space Complexity - O(n)。

```public class Solution {
private Map<Character, String> patternToStr;
private Map<String, Character> strToPattern;

public boolean wordPattern(String pattern, String str) {
int len = pattern.length();
String[] arrOfStr = str.split(" ");
if(len != arrOfStr.length) {
return false;
}
patternToStr = new HashMap<>();
strToPattern = new HashMap<>();
for(int i = 0; i < len; i++) {
char c = pattern.charAt(i);
if(!patternToStr.containsKey(c) && !strToPattern.containsKey(arrOfStr[i])) {
patternToStr.put(c, arrOfStr[i]);
strToPattern.put(arrOfStr[i], c);
} else if(patternToStr.containsKey(c) && !arrOfStr[i].equals(patternToStr.get(c))) {
return false;
} else if(strToPattern.containsKey(arrOfStr[i]) && c != strToPattern.get(arrOfStr[i])) {
return false;
}
}

return true;
}
}```

Java:

```public class Solution {
public boolean wordPattern(String pattern, String str) {
if (pattern == null || str == null) {
return false;
}
String[] wordArr = str.split(" ");
if (pattern.length() != wordArr.length) {
return false;
}
Map<Character, String> pToWord = new HashMap<>();
Map<String, Character> wordToP = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char p = pattern.charAt(i);
String word = wordArr[i];
if (!pToWord.containsKey(p)) {
pToWord.put(p, word);
} else if (!pToWord.get(p).equals(word)) {
return false;
}
if (!wordToP.containsKey(word)) {
wordToP.put(word, p);
} else if (!wordToP.get(word).equals(p)) {
return false;
}
}
return true;
}
}```

Java:

```public class Solution {
public boolean wordPattern(String pattern, String str) {
if (pattern == null || str == null) {
return false;
}
String[] words= str.split(" ");
if (pattern.length() != words.length) {
return false;
}
Map<Character, String> ps = new HashMap<>();
Map<String, Character> sp = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
if ((ps.containsKey(c) && !ps.get(c).equals(word))
|| (sp.containsKey(word) && sp.get(word) != c)) {
return false;
}
if (!ps.containsKey(c)) {
ps.put(c, word);
}
if (!sp.containsKey(word)) {
sp.put(word, c);
}
}
return true;
}
}```

```public class Solution {
public boolean wordPattern(String pattern, String str) {
if (pattern == null || str == null) {
return false;
}
String[] words= str.split(" ");
if (pattern.length() != words.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;
}
}```

Update:

```public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length()) return false;
Map<Character, String> ps = new HashMap<>();
Map<String, Character> sp = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
String word = words[i];
if (!ps.containsKey(c)) ps.put(c, word);
else if (!ps.get(c).equals(word)) return false;

if (!sp.containsKey(word)) sp.put(word, c);
else if (sp.get(word) != c) return false;
}
return true;
}
}```

```public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (pattern.length() != words.length) return false;
Map map = new HashMap<>();
for (Integer i = 0; i < words.length; i++) {
if (map.put(words[i], i) != map.put(pattern.charAt(i), i)) return false;
}
return true;
}
}```

Reference:

https://leetcode.com/discuss/62374/8-lines-simple-java

https://leetcode.com/discuss/62876/very-fast-3ms-java-solution-using-hashmap

## 290. Word Pattern的更多相关文章

1. 【leetcode】290. Word Pattern

problem 290. Word Pattern 多理解理解题意!!! 不过博主还是不理解,应该比较的是单词的首字母和pattern的顺序是否一致.疑惑!知道的可以分享一下下哈- 之前理解有误,应该 ...

2. leetcode 290. Word Pattern 、lintcode 829. Word Pattern II

290. Word Pattern istringstream 是将字符串变成字符串迭代器一样,将字符串流在依次拿出,比较好的是,它不会将空格作为流,这样就实现了字符串的空格切割. C++引入了ost ...

3. [LeetCode] 290. Word Pattern 词语模式

Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

4. 290. Word Pattern 单词匹配模式

［抄题］: Given a pattern and a string str, find if str follows the same pattern. Here follow means a fu ...

5. LeetCode 290 Word Pattern（单词模式）（istringstream、vector、map）（*）

翻译 给定一个模式,和一个字符串str.返回str是否符合同样的模式. 这里的符合意味着全然的匹配,所以这是一个一对多的映射,在pattern中是一个字母.在str中是一个为空的单词. 比如: pat ...

6. [LeetCode] 290. Word Pattern 单词模式

Given a pattern and a string str, find if str follows the same pattern. Here follow means a full mat ...

7. LeetCode 290 Word Pattern

Problem: Given a pattern and a string str, find if str follows the same pattern. Here follow means a ...

8. Java [Leetcode 290]Word Pattern

题目描述: Given a pattern and a string str, find if str follows the same pattern. Here follow means a fu ...

9. 【一天一道LeetCode】#290. Word Pattern

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given a ...

## 随机推荐

1. POJ 1681---Painter&#39;s Problem（高斯消元）

POJ   1681---Painter's Problem(高斯消元) Description There is a square wall which is made of n*n small s ...

2. js延迟加载，提升网页加载速度

JS延迟加载,简单例子,不多说: 代码如下: 程序代码 <script language="JavaScript" src="" id="my& ...

3. .NET DLL 保护措施应用实例(百度云分享工具)

最近做了个小工具,将保护措施思路全部应用到了此工具中. 点我下载 “百度分享工具”介绍 大家都知道,在百度云盘中分享文件,只能手工一条条地点击“分享”,如果想分享很多文件,操作会非常辛苦.“百度云分享 ...

4. ORA-16018: cannot use LOG_ARCHIVE_DEST with LOG_ARCHIVE_DEST_n or DB_RECOVERY_FILE_DEST【error收集】

之前一直没有注意一个事情, 关于设置archive归档路径设置的问题. 设置数据库为归档模式的命令: 1.首先要切换到mount状态: 2.执行alter system archivelog; 3.查 ...

5. SPRING源码分析:IOC容器

在Spring中,最基本的IOC容器接口是BeanFactory - 这个接口为具体的IOC容器的实现作了最基本的功能规定 - 不管怎么着,作为IOC容器,这些接口你必须要满足应用程序的最基本要求: ...

6. Windbg查看调用堆栈(k*)

无论是分析程序崩溃原因,还是解决程序hang问题,我们最常查看的就是程序调用堆栈.学会windbg调用堆栈命令,以及理解堆栈中的各个参数的意义就显得至关重要. 上图就是一个典型的Win ...

7. 获取sd卡的总大小和可用大小

8. TabBottomFragmentLayout【自定义底部选项卡区域（搭配Fragment）】

版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 自定义底部选项卡布局LinearLayout类,然后配合Fragment,实现切换Fragment功能. 缺点: 1.底部选项卡区域 ...

9. 关于视频断点续播和H5的本地存储

前段时间,需要在下实现一个视频的断点续播功能,呃,我不会呀,这就很尴尬了.然后呢,在下就想起了一个叫做localStorage的东西.这是个什么东西呢?在网上查阅了一些资料后,在下发现这是webSto ...

10. [Swift]LeetCode375. 猜数字大小 II | Guess Number Higher or Lower II

We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to gues ...