給定一種規(guī)律 pattern 和一個(gè)字符串 str 鲸阻,判斷 str 是否遵循相同的規(guī)律。
這里的 遵循 指完全匹配缨睡,例如鸟悴, pattern 里的每個(gè)字母和字符串 str 中的每個(gè)非空單詞之間存在著雙向連接的對(duì)應(yīng)規(guī)律。
示例1:
輸入: pattern = "abba", str = "dog cat cat dog"
輸出: true
示例 2:
輸入:pattern = "abba", str = "dog cat cat fish"
輸出: false
示例 3:
輸入: pattern = "aaaa", str = "dog cat cat dog"
輸出: false
示例 4:
輸入: pattern = "abba", str = "dog dog dog dog"
輸出: false
說(shuō)明:
你可以假設(shè) pattern 只包含小寫字母奖年, str 包含了由單個(gè)空格分隔的小寫字母细诸。
題解:
這道題還是比較簡(jiǎn)單的,同樣是一道考察hashmap的題陋守。不多說(shuō)震贵,直接上題解,比官方題解更容易理解水评。
public boolean wordPattern(String pattern, String s) {
char[] chars = pattern.toCharArray();
String[] s1 = s.split(" ");
if (s1.length != chars.length) {
return false;
}
Map<Character, String> map = new HashMap<>();
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
String s2 = s1[i];
boolean b = map.containsValue(s2);
String orDefault = map.put(aChar, s2);
if ((orDefault != null && !orDefault.equals(s2)) || (
orDefault == null && b)) {
return false;
}
}
return true;
}
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/word-pattern
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有猩系。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處中燥。