Leetcode 290. Word Pattern

时间:2022-06-22
本文章向大家介绍Leetcode 290. Word Pattern,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82594572

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

1. Description

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/