0
点赞
收藏
分享

微信扫一扫

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<Character, String> map = new HashMap<>();
Set<String> 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
};


举报

相关推荐

0 条评论