跳转至

单词规律⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        vector<string> words;
        stringstream tokenStream(s);
        string word;
        while (tokenStream >> word) words.emplace_back(word);

        if (words.size() != pattern.size()) return false;

        unordered_map<char, string> patternToWord;
        unordered_map<string, char> wordToPattern;

        for (int i = 0; i < pattern.size(); i++) {
            auto from = pattern[i];
            auto to = words[i];

            if (patternToWord.count(from) && patternToWord[from] != to)
                return false;
            patternToWord[from] = to;

            if (wordToPattern.count(to) && wordToPattern[to] != from)
                return false;
            wordToPattern[to] = from;
        }

        return true;
    }
};