Easy
,Hash Table
,String
Given a pattern
and a string s
, find if s
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 s
.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Constraints:
pattern.length
<= 300pattern
contains only lower-case English letters.s.length
<= 3000s
contains only lowercase English letters and spaces ' '
.s
does not contain any leading or trailing spaces.
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
return len(set(pattern)) == len(set(words)) == len(set(zip_longest(pattern, words)))
Yen-Chi ChenSun, Jan 1, 2023
function wordPattern(pattern, s) {
const words = s.split(' ');
const map = new Map();
if (words.length !== pattern.length) return false;
for (let i = 0; i < pattern.length; i++) {
if (map.has(pattern[i])) {
if (map.get(pattern[i]) !== words[i]) return false;
} else {
if ([...map.values()].includes(words[i])) return false;
map.set(pattern[i], words[i]);
}
}
return true;
}
看到樓上的一行超人,羞愧得差點不敢發…
MarsgoatSun, Jan 1, 2023
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
return len(set(pattern)) == len(set(words:=s.split())) == len(set(zip_longest(pattern, words)))
這才是一行好嗎= =
Yen-Chi ChenMon, Jan 1, 2023