美文网首页Leetcode
Leetcode 290. Word Pattern

Leetcode 290. Word Pattern

作者: SnailTyan | 来源:发表于2018-09-10 19:21 被阅读2次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Word Pattern

    2. Solution

    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            vector<string> strs;
            split(str, strs);
            if(pattern.size() != strs.size()) {
                return false;
            }
            unordered_map<char, string> m1;
            unordered_map<string, char> m2;
            for(int i = 0; i < pattern.length(); i++) {
                if(m1.find(pattern[i]) == m1.end()) {
                    m1[pattern[i]] = strs[i];
                }
                else if(m1[pattern[i]] != strs[i]) {
                    return false;
                }
                if(m2.find(strs[i]) == m2.end()) {
                    m2[strs[i]] = pattern[i];
                }
                else if(m2[strs[i]] != pattern[i]) {
                    return false;
                }
            }
            return true;
        }
        
    private:
        void split(string& str, vector<string>& strs) {
            int start = 0;
            for(int i = 0; i < str.length(); i++) {
                if(str[i] == ' ') {
                    strs.push_back(str.substr(start, i - start));
                    start = i + 1;
                }
            }
            strs.push_back(str.substr(start, str.length() - start));
        }
    };
    

    Reference

    1. https://leetcode.com/problems/word-pattern/description/

    相关文章

      网友评论

        本文标题:Leetcode 290. Word Pattern

        本文链接:https://www.haomeiwen.com/subject/tflegftx.html