290. Word Pattern

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(2ms):

 1 class Solution {
 2     public boolean wordPattern(String pattern, String str) {
 3         String[] words = str.split(" ");
 4         if (words.length != pattern.length())
 5             return false;
 6         Map index = new HashMap();
 7         for (Integer i=0; i<words.length; ++i)
 8             if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
 9                 return false;
10         return true;
11     }
12 }

 

posted @ 2018-03-19 20:59  __Meng  阅读(111)  评论(0编辑  收藏  举报