Leetcode - Word Pattern

来源:互联网 发布:蒙特卡洛算法量化 编辑:程序博客网 时间:2024/06/09 19:25

Question

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.


Java Code

//将pattern中的每个字符与str中对应的单词构成一个<key, value>键值对,依次存入map中,//如果遇到与map中已有的映射关系相矛盾的键值对,则判断为假public boolean wordPattern(String pattern, String str) {    String[] value = str.split(" ");    int len = pattern.length();    if(value.length != len) return false;    HashMap<String, String> map = new HashMap<String, String>();    for(int i = 0; i < len; ++i) {        String key = pattern.charAt(i) + "";        if(map.containsKey(key)) {            if(!value[i].equals(map.get(key)))                return false;        }else {            if(map.containsValue(value[i]))                return false;            map.put(key, value[i]);        }    }    return true;}

0 0