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 assumepattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
<Solution>You may assume
這題給一個 pattern,然後去看一個字串裡面的子字串,是否符合 pattern 的分佈
想法如下
- 用兩個 HashMap 分別來記錄 pattern 出現的位置,和子字串的位置
- 如果再遇到已配對過的 pattern 和子字串,其各自記錄的位置不符合的話,就回傳 false
- 如果再遇到已配對過的 pattern 和子字串,其各自記錄的位置符合的話,更新其位置
- 如果pattern 和子字串的數目,對不起來,也回傳 false
C++ (C++的 unordered_map,如果 key 不存在,直接存取的話,會直接創建,其預設int是0)
Java
可以再簡化,因為 HashMap 可以不指定型別
kotlin
Hello everyone, I made an attempt to explain this solution using simple intuitive approach, you can check this out 😉
回覆刪除https://www.youtube.com/watch?v=tRCDoqo0l40