290. Word Pattern

Q: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.

public class WordPattern {
    public boolean wordPattern(String pattern, String str) {
        String[] str1 = str.split(" ");
        if (pattern.length() != str1.length) {
            return false;
        }

        HashMap hm1 = new HashMap<>();
        HashMap hm2 = new HashMap<>();

        for (int i = 0; i < pattern.length(); i++) {
            String p = pattern.charAt(i)+"";
            String s = str1[i];

            if (hm1.containsKey(p)) {
                if(!hm1.get(p).equals(s)){
                    return false;
                }
            }else{
                hm1.put(p, s);
            }

            if(hm2.containsKey(s)){
                if(!hm2.get(s).equals(p)){
                    return false;
                }
            }else{
                hm2.put(s,p);
            }
        }
        return true;
    }
    public static void main(String args[]) {
        WordPattern s = new WordPattern();
        String p = "abba";
        String str = "dog dog dog dog";
        System.out.println(s.wordPattern(p, str));
    }
}

用两个hashmap来做,字符串数组&字符,分别是value&key。
pattern有多少种不同的字符,str也有多少种不同的word。如果我们将映射写成字符对的形式,比如 (‘a’,’dog’) 表示pattern中字符’a’映射到str中’dog’。反之亦然。

你可能感兴趣的:(Leetcode,HashMap)