给定一种规律 pattern
和一个字符串 s
,判断 s
是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern
里的每个字母和字符串 s
中的每个非空单词之间存在着双向连接的对应规律。
示例1:
1 2
| 输入: pattern = "abba", s = "dog cat cat dog" 输出: true
|
示例 2:
1 2
| 输入:pattern = "abba", s = "dog cat cat fish" 输出: false
|
示例 3:
1 2
| 输入: pattern = "aaaa", s = "dog cat cat dog" 输出: false
|
提示:
1 <= pattern.length <= 300
pattern
只包含小写英文字母
1 <= s.length <= 3000
s
只包含小写英文字母和 ' '
s
不包含 任何前导或尾随对空格
s
中每个单词都被 单个空格 分隔
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public boolean wordPattern(String pattern, String str) { String[] words = str.split(" "); if(pattern.length() != words.length){ return false; } Map<Character, String> map1 = new HashMap<>(); Map<String, Character> map2 = new HashMap<>();
for(int i = 0; i < pattern.length(); i++){ char c = pattern.charAt(i); String s = words[i]; if(map1.containsKey(c) && !map1.get(c).equals(s) || map2.containsKey(s) && map2.get(s) != c){ return false; } map1.put(c, s); map2.put(s, c);
} return true; } }
|