问题:
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.
解释:本问题要求做到一一对应,所以可以想到Java中的Map集合
问题还是比较简单的,关键就是细节方面,要把所有的问题都要考虑进去
代码:
import java.util.*;
public class Solution {
public boolean wordPattern(String pattern, String str) {
Map map = new HashMap();
char c;
String[] a = str.split(" ");
if(pattern.length() != a.length){
return false;
}
map.put(pattern.charAt(0),a[0]);
for(int i=1;i<a.length;i++){
c=pattern.charAt(i);
if(!map.containsKey(c) && !map.containsValue(a[i])){
map.put(c,a[i]);
}else if(!map.containsKey(c) && map.containsValue(a[i])){
return false;
}else{
String s = (String)map.get(c);
if(!s.equals(a[i])){
return false;
}
}
}
return true;
}
}