Given a pattern
and a string str
, find if str
follows the same pattern.git
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty word in str
.github
Example 1:spa
Input: pattern = , str = Output: true"abba""dog cat cat dog"
Example 2:code
Input:pattern = , str = Output: false"abba""dog cat cat fish"
Example 3:leetcode
Input: pattern = , str = Output: false"aaaa""dog cat cat dog"
Example 4:get
Input: pattern = , str = Output: false"abba""dog dog dog dog"
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.string
//對於匹配的問題 感受通常用map都是能夠的 public static boolean wordPattern(String pattern, String str) { boolean result = true; Map<Character, String> map = new HashMap<>(); String arrays[] = str.split(" "); if(arrays.length != pattern.length()){ return false; } for (int i = 0; i < pattern.length(); i++) { if (map.containsKey(pattern.charAt(i))) { String value = map.get(pattern.charAt(i)); if (!value.equals(arrays[i])) { result = false; break; } } else { if(map.containsValue(arrays[i])) { return false; } map.put(pattern.charAt(i), arrays[i]); } } return result; }
//化簡一下 直接經過put操做判斷 簡化了contains操做 public static boolean wordPattern2(String pattern, String str) { String[] words = str.split(" "); if (words.length != pattern.length()) { return false; } Map index = new HashMap(); for (Integer i=0; i<words.length; ++i) { if (index.put(pattern.charAt(i), i) != index.put(words[i], i)) { return false; } } return true; }
git:https://github.com/woshiyexinjie/leetcode-xinit