题目:

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. InputStream和OutputStream与String之间的转换

    //1.字符串转inputstream String str="aaaaa"; InputStream in = new ByteArrayInputStream(str.getB ...

  2. c读取文本文档

    想数一下文本文档一共有多少行,写了个小程序 1.用fopen()以只读方式打开文件 2.用fgetc()获取文件流中的字符内容 3.如果字符内容为'\n'换行符,count++ 最后输出count的值 ...

  3. 11.5Daily Scrum

    人员 任务分配完成情况 明天任务分配 王皓南 实现网页上视频浏览的功能.研究相关的代码和功能.811 数据库测试 申开亮 实现网页上视频浏览的功能.研究相关的代码和功能.812 实现视频浏览的功能 王 ...

  4. 问题:ldconfig

    显示加载库文件libjli.so时候出错. 解决办法 1.find / -name 'libjli.so'文件 路径在:/data0/home/app/act/jdk/jdk1.7.0_15/jre/ ...

  5. Java 字符编码归纳总结

    String newStr = new String(oldStr.getBytes(), "UTF-8");       java中的String类是按照unicode进行编码的 ...

  6. BCP command usage in SQL Server

    The bcp Command-Line Utility You use the bcp (bulk copy program) tool to address the bulk movement o ...

  7. UVALive - 6575 Odd and Even Zeroes 数位dp+找规律

    题目链接: http://acm.hust.edu.cn/vjudge/problem/48419 Odd and Even Zeroes Time Limit: 3000MS 问题描述 In mat ...

  8. Codeforces Round #349 (Div. 1) B. World Tour 最短路+暴力枚举

    题目链接: http://www.codeforces.com/contest/666/problem/B 题意: 给你n个城市,m条单向边,求通过最短路径访问四个不同的点能获得的最大距离,答案输出一 ...

  9. C实现面向对象封装、继承、多态

    参考资料:      http://blog.chinaunix.net/uid-26750235-id-3102371.html      http://www.eventhelix.com/rea ...

  10. Combox 实现百度收索框效果

    标题中所谓百度收缩框效果,就是在输入数据的时候,自动提示,来张图就明白了: 用Combox来实现这个功能只是需要设置三个A开头的属性就OK了:AutoCompleteSource.AutoComple ...