290. 单词规律。
给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = “abba”, s = “dog cat cat dog”
输出: true
示例 2:
输入:pattern = “abba”, s = “dog cat cat fish”
输出: false
示例 3:
输入: pattern = “aaaa”, s = “dog cat cat dog”
输出: false
析:
用map映射解决问题。
map的put()方法:return the previous value associated with <tt>key</tt>
解:
public class Test {public static void main(String[] args) {String pattern = "ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccdd";String s = "s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s s t t";Test test = new Test();boolean res = test.wordPattern(pattern, s);System.out.println(res);}public boolean wordPattern(String pattern, String s) {String[] words = s.split(" ");if (pattern.length() != words.length) {return false;}Map<Object, Integer> map = new HashMap<>();// 这里注意使用Integer,如果使用int,当数字超过128,!=就自动成立了for (Integer i = 0; i < words.length; i++) {// return the previous value associated with keyif (map.put(pattern.charAt(i), i) != map.put(words[i], i)) {return false;}}return true;}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
