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;
}
}