Skip to content

Files

Latest commit

fb82080 · Mar 13, 2021

History

History
67 lines (55 loc) · 2.14 KB

290.md

File metadata and controls

67 lines (55 loc) · 2.14 KB

【中规中矩】290. 单词规律(哈希表多语言实现)

解题思路

首先需要把s拆分成为单词数组。C++可以用stringstream 拆分,Python,Java直接split就可以了。然后建立两个map表示char到单词string的映射,及单词string到char的映射。逐一验证每个char对应唯一的string,每个string对应唯一的char即可。

代码

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        stringstream ss(s);
        vector<string> strs;
        string str;
        while (ss >> str) {
            strs.push_back(str);
        }
        unordered_map<char, string> char2Str;
        unordered_map<string, char> str2Char;
        if (pattern.size() != strs.size()) {
            return false;
        }

        int N = pattern.size();
        for (int i = 0; i < N; i++) {
            if (char2Str.count(pattern[i])) {
                if (char2Str[pattern[i]] != strs[i]) {
                    return false;
                }
            } else if (str2Char.count(strs[i])) {
                if (str2Char[strs[i]] != pattern[i]) {
                    return false;
                }
            }
            char2Str[pattern[i]] = strs[i];
            str2Char[strs[i]] = pattern[i];
        }

        return true;
    }
};
class Solution(object):
    def wordPattern(self, pattern, s):
        str2Char = dict()
        char2Str = dict()
        words = s.split()
        if len(pattern) != len(words):
            return False
        
        for ch, word in zip(pattern, words):
            if (word in str2Char and str2Char[word] != ch) or (ch in char2Str and char2Str[ch] != word):
                return False
            str2Char[word] = ch
            char2Str[ch] = word
        
        return True

点我赞赏作者

github 题解

Image