题目:

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. 微软职位内部推荐-Senior Software Engineer-Office Incubation

    微软近期Open的职位: Office China team is looking for experienced engineers to improve consumer experience i ...

  2. 字符串流sstream[part2/使用同一个字符串流反复读写数据]

    stringstream构造函数会特别消耗内存,似乎不打算主动释放内存(或许是为了提高效率),如果你要在程序中使用同一个流反复读写大量数据,将会造成大量的内部消耗,因此建议:    1:调用clear ...

  3. 修改placeholder文字颜色

    .area_ipt ::-webkit-input-placeholder { /* WebKit browsers */ color:#258aca; } .area_ipt :-moz-place ...

  4. Java多线程时内存模型

    1. 概述 多任务和高并发是衡量一台计算机处理器的能力重要指标之一.一般衡量一个服务器性能的高低好坏,使用每秒事务处理数(Transactions Per Second,TPS)这个指标比较能说明问题 ...

  5. 图解SQL的Join(转摘)

    转摘网址:http://coolshell.cn/articles/3463.html 对于SQL的Join,在学习起来可能是比较乱的.我们知道,SQL的Join语法有很多inner的,有outer的 ...

  6. UVALive - 7368 Airports DAG图的最小路径覆盖

    题目链接: http://acm.hust.edu.cn/vjudge/problem/356788 Airports Time Limit: 3000MS 问题描述 An airline compa ...

  7. Drawing with GoogLeNet

    Drawing with GoogLeNet In my previous post, I showed how you can use deep neural networks to generat ...

  8. 移动端页面调试工具——UC浏览器开发者版

    在移动页面的开发中,我们很难像PC端那样很方便的调试,网上也有各种各样的调试方式.但在工作中,我主要还是用chorme自带的模拟器来模拟各种移动设备,但是用久了之后发现毕竟是模拟的,与真机调试还是会有 ...

  9. HDOJ 1050 Moving Tables

    Moving Tables Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tot ...

  10. Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service

    实现目标 http://localhost:9000/rs/roomservice 为入口, http://localhost:9000/rs/roomservice/room为房间列表, http: ...