LeetCode:Word Pattern

problem:

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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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.

Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Solution:
public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (pattern.isEmpty() || str.isEmpty()) {
            return false;
        }
         
        String[] s = str.split(" ");
        if (s.length != pattern.length()) {
            return false;
        }
         
        HashMap<Character, String> hashMap = new HashMap<Character, String>();
        for (int i = 0; i < pattern.length(); i++) {
            if (hashMap.containsKey(pattern.charAt(i))) {
                if (!hashMap.get(pattern.charAt(i)).equals(s[i])) {
                    return false;
                }
            } else if (hashMap.containsValue(s[i])) {
                return false;
            } else {
                hashMap.put(pattern.charAt(i), s[i]);
            }
        }
         
        return true;
        
    }
}
原文地址:https://www.cnblogs.com/xiaoying1245970347/p/5178433.html