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 1:
Input: pattern ="abba"
, str ="dog cat cat dog"
Output: trueExample 2:
Input:pattern ="abba"
, str ="dog cat cat fish"
Output: falseExample 3:
Input: pattern ="aaaa"
, str ="dog cat cat dog"
Output: falseExample 4:
Input: pattern ="abba"
, str ="dog dog dog dog"
Output: false
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters that may be separated by a single space.
单词规律。
给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-pattern
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题的做法不难想,需要用hashmap记录pattern里面每个字母跟str里面每个单词的对应关系。注意如果出现一个字母对应的单词跟hashmap里记录的不一致,则返回false;同时,如果出现一个已经被hashmap记录过的单词居然跟别的字母匹配,那样也是错的。这个case很容易被遗忘。
时间O(n^2) - 因为hashmap在判断containsValue()的时候,是O(n)级别的
空间O(n)
Java实现
1 class Solution { 2 public boolean wordPattern(String pattern, String s) { 3 // corner case 4 String[] array = s.split(" "); 5 if (pattern.length() != array.length) { 6 return false; 7 } 8 9 // normal case 10 HashMap<Character, String> map = new HashMap<>(); 11 for (int i = 0; i < pattern.length(); i++) { 12 char cur = pattern.charAt(i); 13 if (map.containsKey(cur)) { 14 if (map.get(cur).equals(array[i])) { 15 continue; 16 } else { 17 return false; 18 } 19 } else { 20 if (!map.containsValue(array[i])) { 21 map.put(cur, array[i]); 22 } else { 23 return false; 24 } 25 } 26 } 27 return true; 28 } 29 }