290. Word Pattern

网友投稿 555 2022-11-11

290. Word Pattern

290. Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.

Examples: pattern = “abba”, str = “dog cat cat dog” should return true. pattern = “abba”, str = “dog cat cat fish” should return false. pattern = “aaaa”, str = “dog cat cat dog” should return false. pattern = “abba”, str = “dog dog dog dog” should return false. Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution { public boolean wordPattern(String pattern, String str) { String[] strs = str.split(" "); if(pattern.length() != strs.length) return false; Map map = new HashMap<>(); Set unique = new HashSet<>(); for(int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if(map.containsKey(c)) { if(!map.get(c).equals(strs[i])) return false; } else { if(unique.contains(strs[i])) return false; map.put(c, strs[i]); unique.add(strs[i]); } } return true; }}

/** * @param {string} pattern * @param {string} str * @return {boolean} */var wordPattern = function(pattern, str) { const pArr = pattern.split('') const sArr = str.split(' ') const pLen = pArr.length const sLen = sArr.length if (pLen !== sLen) { return false } const mapP = new Map() const mapS = new Map() for (let i = 0; i < pLen; i++) { const pat = pArr[i] const s = sArr[i] if (!mapP.has(pat)) { mapP.set(pat, s) } else { if (mapP.get(pat) !== s) { return false } } if (!mapS.has(s)) { mapS.set(s, pat) } else { if (mapS.get(s) !== pat) { return false } } } return true};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:669. Trim a Binary Search Tree
下一篇:728. Self Dividing Numbers
相关文章

 发表评论

暂时没有评论,来抢沙发吧~