# Leetcode 290 Word Pattern.

Leetcode 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:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
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.

At first, I misunderstand what the problem want us to do, so I have the code like this(WRONG):

``````
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] splitstr=new String[pattern.length()];
splitstr=str.split(" ");
char[] patternchar=pattern.toCharArray();
boolean[] flag=new boolean[pattern.length()];
for(int i=0;i < flag.length;i++){
flag[i]=false;
}

for(int i=0;i < splitstr.length;i++){
char[] splitstrchar=splitstr[i].toCharArray();
for(int j=0;j < splitstrchar.length;j++){
if(patternchar[i]==splitstrchar[j]){
flag[i]=true;
}
}
}

for(int i=0;i < flag.length;i++){
if(flag[i]==false){
return false;
}
}
return true;
}
}
``````

What I thought is if each word contain the words from the pattern one by one.

BTW, the code is right if the question asks that way.

``````

public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] word=str.split(" ");
if(pattern.length()!=word.length){
return false;
}
Map index=new HashMap();
for(Integer i=0;i < word.length;++i){
if(index.put(pattern.charAt(i), i) != index.put(word[i], i)){
return false;
}
}
return true;
}
}
``````

Integer can not be replaced by int. Because there's no autoboxing-same-value-to-different-objects-problem anymore