您的位置:首页 > 其它

Leetcode - Word Pattern

2016-05-05 18:24 316 查看

Question

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 Code

//将pattern中的每个字符与str中对应的单词构成一个<key, value>键值对,依次存入map中,
//如果遇到与map中已有的映射关系相矛盾的键值对,则判断为假
public boolean wordPattern(String pattern, String str) {
String[] value = str.split(" ");
int len = pattern.length();
if(value.length != len) return false;

HashMap<String, String> map = new HashMap<String, String>();
for(int i = 0; i < len; ++i) {
String key = pattern.charAt(i) + "";
if(map.containsKey(key)) {
if(!value[i].equals(map.get(key)))
return false;
}else {
if(map.containsValue(value[i]))
return false;
map.put(key, value[i]);
}
}

return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode pattern word