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 }
原文地址:https://www.cnblogs.com/mengchunchen/p/8604746.html