目录
题目
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.
Example:
- pattern = “abba”, str = “dog cat cat dog” should return true.
- pattern = “abba”, str = “dog cat cat fish” should return false.
- pattern = “aaaa”, str = “dog cat cat dog” should return false.
- pattern = “abba”, str = “dog dog dog dog” should return false.
Note:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
解决方案
1 | import java.util.Hashtable; |
注意事项
1.使用一个Hashtable,key为模式字符串,value为待检测字符串。遍历两个输入字符串,如果key值pattern.charAt(i)不存在,且arr[i]的值在table中不存在,则可以将pattern.charAt(i)和arr[i]对应起来,存入table。
- 如果key值pattern.charAt(i)存在,则将其value值和当前arr[i]比较,如不同,说明模式未能正确匹配,返回false。