题目:

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. C++中数组求偏移量计算公式

    已知数组:type A[10][5]A[0][0] --A[8][4]面试常考:数组定义A[0....x][0...y]已知A[m][n] --求A[k][l]的地址:    &A[m][n] ...

  2. Google Volley: How to send a POST request with Json data?

    sonObjectRequest actuallyaccepts JSONObject as body. From http://arnab.ch/blog/2013/08/asynchronous- ...

  3. PSP0表格二

    一 项目计划日志 周活动总结表 姓名: 陆宇 日期:2015. 3. 21 日期       任务 听课 编写程序 阅读课本 准备考试 日总计/(min) 周日 60 30 90 周一 300 0 1 ...

  4. j2SE基回顾(一)

    1. 九种基本数据类型的大小,以及他们的封装类. 2. Switch能否用string做参数? 3. equals与==的区别. 4. Object有哪些公用方法? Object是所有类的父类,任何类 ...

  5. js判断浏览器滚动条是否拉到底

    $(window).scroll(function(){ // 当滚动到最底部以上n像素时, 加载新内容 if ($(document).height() - $(this).scrollTop() ...

  6. 【Search a 2D Matrix】cpp

    题目: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the f ...

  7. IIS8托管WCF服务

    WCF服务程序本身不能运行,需要通过其他的宿主程序进行托管才能调用WCF服务功能,常见的宿主程序有IIS,WAS,Windows服务,当然在学习WCF技术的时候一般使用控制台应用程序或WinForm程 ...

  8. 7-Highcharts曲线图之分辨带

    <!DOCTYPE> <html lang='en'> <head> <title>7-Highcharts曲线图之分辨带</title> ...

  9. 系统使用 aspose.cell , 使得ashx第一次访问会变很慢

      网站放在IIS后, 在网站第一次访问后.  回收应用程序池 第一次访问aspx页面还是比较快.   但第一次访问ashx会很慢.   后发现原因: aspose.cell的5.3...版本. 的原 ...

  10. Sublime搭建nodejs环境(windows)

    1.下载nodejs,并安装ok后,配置好环境变量. 2.下载sublime text3 3.在package install 包中新增node插件(或者直接去SublimeText-Nodejs插件 ...