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.
大概题意: 1、对应的pattern - str是可以用hashmap组成的键值对;
2、主要判断的是:map中是否存在key :
1、若不存在key,但存在value,则返回false;
2、若存在key, 但是value与str的对应字符串不等,返回false;
若都不存在,就添加新的 k-v对;
public class Solution {
/**
* 字符串模式匹配
* @param pattern
* @param str
* @return
*/
public boolean wordPattern(String pattern, String str) {
if (pattern.isEmpty() || str.isEmpty())
return false;
String[] string = str.split(" ");
if (pattern.length() != string.length)
return false;
HashMap<Character, String> hashMap = new HashMap<Character, String>();
for (int i = 0; i < pattern.length(); i++) {
if (hashMap.containsKey(pattern.charAt(i))) {
if (!hashMap.get(pattern.charAt(i)).equals(string[i]))
return false;
} else if (hashMap.containsValue(string[i]))
return false;
else
hashMap.put(pattern.charAt(i), string[i]);
}
return true;
}
}
总结: 1、splith函数:在java.lang包中有String.split()方法,返回是一个数组 (http://www.cnblogs.com/liubiqu/archive/2008/08/14/1267867.html)
2、HashMap的各种操作:详见 http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4
3、字符串操作: 详见 http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4