2015年10月5日星期一

Word Pattern

Given a pattern and a string str, find if str follows the same pattern.
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:

  1. Both pattern and str contains only lowercase alphabetical letters.
  2. Both pattern and str do not have leading or trailing spaces.
  3. Each word in str is separated by a single space.
  4. Each letter in pattern must map to a word with length that is at least 1.





Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
public class Solution {
    public boolean wordPattern(String pattern, String str) {
        if (pattern == null || str == null || pattern.length() == 0 || str.length() == 0) {
            return false;
        }
        String tokens[] = str.split(" ");
        if (pattern.length() != tokens.length) return false;
        HashMap<Character, String> map1 = new HashMap<Character, String>();
        HashSet<String> set = new HashSet<String>();
        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            if (map1.containsKey(c)) {
                if (!map1.get(c).equals(tokens[i])) {
                    return false;
                }
            } else {
                if (set.contains(tokens[i])) {
                    return false;
                }
                map1.put(c, tokens[i]);
                set.add(tokens[i]);
            }
        }
        return true;
    }
}

没有评论:

发表评论