1. 程式人生 > 其它 >Leetcode刷題筆記 290. 單詞規律

Leetcode刷題筆記 290. 單詞規律

技術標籤:leetcodeleetcode

290. 單詞規律

時間:2020年12月16日
知識點:雜湊表、細節
題目連結:https://leetcode-cn.com/problems/word-pattern/

題目
給定一種規律 pattern 和一個字串 str ,判斷 str 是否遵循相同的規律。

這裡的 遵循 指完全匹配,例如, pattern 裡的每個字母和字串 str 中的每個非空單詞之間存在著雙向連線的對應規律。

示例1:

輸入: pattern = “abba”, str = “dog cat cat dog”
輸出: true

示例 2:
輸入:pattern = “abba”, str = “dog cat cat fish”

輸出: false

示例 3:
輸入: pattern = “aaaa”, str = “dog cat cat dog”
輸出: false

示例 4:
輸入: pattern = “abba”, str = “dog dog dog dog”
輸出: false

說明:

  • 你可以假設 pattern 只包含小寫字母, str 包含了由單個空格分隔的小寫字母。

解法

  1. 解法並不難 還是有很多小細節需要注意
  2. 從示例4可以看出 需要兩個雜湊表 存對應的關係 相同的單詞不能對應不同的模式字元
  3. 需要考慮 pattern 比 str 長的情況
  4. 也要考慮 str 比 pattern 長的情況
  5. 注意 捨棄空格的操作

程式碼

#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map<char, string> ump_c_s;
        unordered_map<string, char> ump_s_c;
        int j = 0,s_end = s.length();
        for
(int i = 0 ; i < pattern.length(); i++){ if(j > s_end) {return false;} char x = pattern[i]; string tmp = ""; while(j < s_end && s[j] != ' '){ tmp += s[j]; j++; } j++; if(ump_c_s.find(x) != ump_c_s.end()){ if(ump_c_s[x] != tmp) return false; }else if(ump_c_s.find(x) == ump_c_s.end()) ump_c_s[x] = tmp; if(ump_s_c.find(tmp) != ump_s_c.end()){ if(ump_s_c[tmp] != x) return false; }else if(ump_s_c.find(tmp) == ump_s_c.end()) ump_s_c[tmp] = x; } return j >= s_end; } }; int main() { string pattern = "abba"; string s = "dog dog dog dog"; Solution S; cout<<S.wordPattern(pattern, s)<<endl; return 0; }

今天也是愛zz的一天哦!