题目:

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.

链接: http://leetcode.com/problems/word-pattern/

题解:

跟Isomophic Strings基本一样,使用两个hashmap保持pattern char和string的的一对一关系。  看到Discuss里也有使用一个HashMap的,非常巧妙,对put研究得很深。二刷要使用更好的方法。

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;
}
}

二刷:

和一刷方法一样,也和Isomophic Strings一样

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;
}
}

更好的写法来自Stefan Pochmann。

这里比较的是pattern里面的char, 和words里面的word上一次出现的位置是否相同。原理和Isomophic Strings一样。

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:

重写了一下使用两个map

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;
}
}

利用Map.put,同时遍历pattern和words。 这里map.put()返回的是上一次保存的value,也就是上一次的index i

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;
}
}

四刷:

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

https://docs.oracle.com/javase/6/docs/api/java/util/Map.html#put%28K,%20V%29

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. Xcode 7遇到 App Transport Security has blocked a cleartext HTTP 错误

    今天用Xcode 7 创建新项目用到 URL 发送请求时,报下面的错: “App Transport Security has blocked a cleartext HTTP (http://) r ...

  2. 【每日scrum】NO.3

    1.感觉需求分析没有想象的那么简单,今天由于某些原因没有完成.

  3. 二、break,continue区别

    break:作用于switch,和循环语句,用于跳出,或者称为结束 break语句单独存在,下面不要定义其他语句,因为执行不到,编译会失败,当循环套时,break会跳出当前所在循环,要跳出外部循环,只 ...

  4. camera render texture 游戏里的监控视角

    Camera里: 新建render texture并拖入到target texture里 新建材质球 拖入render texture      camera里的视角会在材质球上出现  新建一个pla ...

  5. 【Populating Next Right Pointers in Each Node II】cpp

    题目: Follow up for problem "Populating Next Right Pointers in Each Node". What if the given ...

  6. ubuntu(Eclipse+JDK) 自动安装脚本

    sudo rm -rf jdk1.8.0_40sudo rm -rf /usr/lib/jvm sudo tar -zxvf jdk-8u40-linux-i586.tar.gzsudo mkdir ...

  7. Netsharp快速入门(之10) 销售管理(插件、资源、业务建模)

    作者:秋时 杨昶   时间:2014-02-15  转载须说明出处 第4章     销售模块开发 4.1     创建插件和资源 参考基础档案的开发 4.2     创建业务模型 Netsharp工具 ...

  8. 【BZOJ】【3301】【USACO2011 Feb】Cow Line

    康托展开 裸的康托展开&逆康托展开 康托展开就是一种特殊的hash,且是可逆的…… 康托展开计算的是有多少种排列的字典序比这个小,所以编号应该+1:逆运算同理(-1). 序列->序号:( ...

  9. Leetcode#109 Convert Sorted List to Binary Search Tree

    原题地址 跟Convert Sorted Array to Binary Search Tree(参见这篇文章)类似,只不过用list就不能随机访问了. 代码: TreeNode *buildBST( ...

  10. NYOJ-289 苹果 289 AC(01背包) 分类: NYOJ 2014-01-01 21:30 178人阅读 评论(0) 收藏

    #include<stdio.h> #include<string.h> #define max(x,y) x>y?x:y struct apple { int c; i ...