[LeetCode] #290 單詞規律
阿新 • • 發佈:2021-09-16
[LeetCode] #290 單詞規律
給定一種規律 pattern 和一個字串 str ,判斷 str 是否遵循相同的規律。
這裡的 遵循 指完全匹配,例如, pattern 裡的每個字母和字串 str 中的每個非空單詞之間存在著雙向連線的對應規律。
輸入: pattern = "abba"
, str = "dog cat cat dog"
輸出: true
使用兩個HashMap表示相互的對映關係
class Solution { public boolean wordPattern(String pattern, String s) { String[] split= s.split(" "); if (split.length != pattern.length()) return false; HashMap<Character,String> map1 = new HashMap<>(); String t1 = null,t2 = null; for(int i = 0; i < pattern.length(); i++){ t1 = map1.put(pattern.charAt(i),split[i]); t2= map1.get(pattern.charAt(i)); if(t1 != null && !t1.equals(t2)) return false; } HashMap<String,Character> map2 = new HashMap<>(); Character s1 = null,s2 = null; for(int i = 0; i < pattern.length(); i++){ s1 = map2.put(split[i],pattern.charAt(i)); s2= map2.get(split[i]); if(s1 != null && !s1.equals(s2)) return false; } return true; } }
使用一個HashMap,利用下標i作為對映的中間聯絡
class Solution { public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if (words.length != pattern.length()) return false; Map<Object, Integer> map = new HashMap<>(); for (Integer i = 0; i < words.length; i++) if (map.put(pattern.charAt(i), i) != map.put(words[i], i)) return false; return true; } }
知識點:無
總結:無