跳转至

290. Word Pattern

Leetcode Hash Table

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.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

分析

这道题目是LeetCode 205. Isomorphic Strings的扩展。在Q205中,字符和字符存在一一对应关系。这里字符和字符串存在一一对应关系。但是它们的实质是相同的。在Q205中,有两种方法来解决问题;在这道题目中这两种方法仍旧适用,只需要稍微改编一下即可。

方法1, 使用哈希表来存储patternstr的一一对应关系。

public boolean wordPattern(String pattern, String str) {
    String[] strs = str.trim().split("\\s+");
    if (pattern.length() != strs.length) return false;

    Map<Character, String> map = new HashMap<>();
    Set<String> set = new HashSet<>();
    for (int i = 0; i < pattern.length(); i++) {
        if (map.containsKey(pattern.charAt(i))) {
            if (!map.get(pattern.charAt(i)).equals(strs[i])) return false;
        } else {
            if (!set.add(strs[i])) return false;
            map.put(pattern.charAt(i), strs[i]);
        }
    }

    return true;    
}

方法2, 存储下标

public boolean wordPattern(String pattern, String str) {
    String[] words = str.split(" ");
    if (words.length != pattern.length())
        return false;
    Map index = new HashMap();
    for (Integer i = 0; i<words.length; ++i)
        if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
            return false;
    return true;   
}

上面的代码中Map缺失了Generics, 但是可以把两种类型的数据(Character, String)都放进去。