Tuesday, December 1, 2015

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

就是简单的双映射

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        String[] A= str.split("\\s+");
        Map<Character, String> map1 = new HashMap();
        Map<String,Character> map2 = new HashMap();
        if(pattern.length() != A.length)
            return false;
        for(int i =0;i< pattern.length();i++){
            char ch = pattern.charAt(i);
            String ss = A[i];
            if(map1.containsKey(ch) ){
                if(! map1.get(ch).equals(ss))
                    return false;
            }
            map1.put(ch,ss);
            // check reverse
            if(map2.containsKey(ss)){
                if(! map2.get(ss).equals(ch))
                    return false;
            }
            map2.put(ss, ch);
        }
        return true;
    }
}

Errors:
好久没刷题了, check String相等的时候, 直接用了等号

No comments:

Post a Comment