题目链接
单词规律
题目描述
注意点
- pattern只包含小写英文字母
- s只包含小写英文字母和 ’ ’
- s不包含任何前导或尾随对空格
- s中每个单词都被 单个空格 分隔
解答思路
- 本题与上一次同构字符串类似,思路可以参照同构字符串
代码
class Solution {public boolean wordPattern(String pattern, String s) {String[] words = s.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 word = words[i];if (map1.get(c) != null && !map1.get(c).equals(word)) {return false;}if (map2.get(word) != null && map2.get(word) != c) {return false;}map1.put(c, word);map2.put(word, c);}return true;}
}
关键点
- 无