LeetCode-Word Pattern

LiBlog發表於2016-09-03

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.

Solution:

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (str.isEmpty() && pattern.isEmpty()) return true;
        if (str.isEmpty() || pattern.isEmpty()) return false;
        
        String[] map = new String[26];
        Arrays.fill(map,"");
        String[] words = str.split(" ");
        HashSet<String> assigned = new HashSet<String>();
        
        if (pattern.length()!=words.length) return false;
        
        for (int i=0;i<pattern.length();i++){
            char code = pattern.charAt(i);
            if (!map[code-'a'].isEmpty()){
                // code.word != word, it is wrong
                if (!map[code-'a'].equals(words[i])){
                    return false;
                }
            } else {
                // code.word is empty but word has been assigned to another code, it is wrong.
                if (assigned.contains(words[i])){
                    return false;
                }
                assigned.add(words[i]);
                map[code-'a'] = words[i];
            }
        }
        return true;
    }
}

 

相關文章