Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 290. Word Pattern

Rain Hu

290. Word Pattern


一、題目

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 non-empty word in s.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Hash Table

vector<string> split(string& str, char del){
    stringstream ss(str);
    string item;
    vector<string> res;
    while (getline(ss, item, del)){
        if (!item.empty()){
            res.push_back(item);
        }
    }
    return res;
}
bool wordPattern(string pattern, string s) {
    unordered_map<char, string> map;
    unordered_set<string> st;
    vector<string> svec = split(s, ' ');                // 將 s 以空白拆開成陣列
    if (pattern.length() != svec.size()) return false;  // 檢查陣列的個數是否與 pattern 的長度相符
    for (int i = 0; i < svec.size(); i++) {
        char& c = pattern[i];
        if (!map.count(c)) {                            // 定義第一次出現的 pattern 
            if (st.count(svec[i])) return false;        // 如果該字串已經被定義過 pattern 則為 false
            map[c] = svec[i];                           // 定義 pattern
            st.insert(svec[i]);                         // 將定義過的字串記錄下來
        } else {
            if (map[c] != svec[i]) return false;        // 定義的 pattern 不符
        }
    }
    return true;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2520. Count the Digits That Divide a Number
Next
[C#] Yield Return