# 290. Word Pattern

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.

note：

class Solution {
public:
bool wordPattern(string pattern, string str) {

map<char, int> pat;
map<string, int> st;
int i = 0;
int n = pattern.size();
istringstream in(str);  //从字符串中分离出单词

for(string word; in >> word; ++i){  //in >> word 调用in函数，将每个单词赋给word变量
if(i==n || pat[pattern[i]] != st[word]){
return false;
}
pat[pattern[i]] = st[word] = i+1;
}

return i==n;
}
};

java版：利用字符串api处理字符串

public class Solution {
public boolean wordPattern(String pattern, String str) {

String[] words = str.split(" ");
if(words.length != pattern.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;
}
}


#### leetcode 290: Word Pattern

2015-10-06 16:10:22

#### leetcode 290 Word Pattern C++

2016-06-07 21:44:23

#### 【LeetCode-290】Word Pattern（C++）

2015-11-16 16:10:02

#### [leetcode-290]Word Pattern(java)

2015-10-06 10:39:37

#### 290. Word Pattern [easy] (Python)

2016-06-16 17:48:27

#### LeetCode 290. Word Pattern（单词模式）

2016-04-16 00:51:13

#### LeetCode-290. Word Pattern

2016-04-06 11:46:06

#### [290]Word Pattern

2015-10-11 11:43:46

#### [LeetCode 290] Word Pattern

2015-10-09 11:44:41

#### leetcode_c++：哈希：word pattern(290)

2016-07-10 14:59:02