1. 题目描述
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.
给定一个模式和一个使用空格分割的字符串,验证两个模式是否相同。
2. 解题思路
首先发现是两个模式有一个对应关系,如
3. Code
import java.util.HashMap;
import java.util.HashSet;
public class Solution {
public boolean wordPattern(String pattern, String str) {
// 分割字符串
String [] strs = str.split(" ");
// 两个模式长度不等,则一定不同
if (pattern.length() != strs.length)
return false;
// 用于存储pattern[i]到strs[i]的映射关系
HashMap<String, String> hashMap = new HashMap<>();
// 用于验证(a,dog)(b,dog)的情况
HashSet<String> hashSet = new HashSet<>();
for (int i = 0; i < pattern.length(); ++i)
{
String k = "" + pattern.charAt(i);
String v = strs[i];
// 如果key不存在
if(!hashMap.containsKey(k))
{
// 但是set中包含value
if(hashSet.contains(v))
return false;
// 加入key,value
hashMap.put(k,v);
hashSet.add(v);
}
else
{
// key存在查看对应的值是否相等
if(!v.equals(hashMap.get(k)))
{
return false;
}
}
}
return true;
}
}