[leetcode]290. Word Pattern

[leetcode]290. Word Pattern


Analysis

周五啦,端午小长假要开始啦~—— [嘻嘻~]

Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
就是判断pattern 和 str中的字符和字符串是否一一对应,很显然想到用map解决,但是要注意的是需要建立两个map,双向对应才可以!!!!

Implement

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        map<string, char> dic1;
        map<char, string> dic2;
        int len1 = pattern.length();
        int len2 = str.length();
        vector<string> str1;
        string tmp = "";
        for(int i=0; i<len2; i++){
            if(str[i] < 'a' || str[i] > 'z'){
                str1.push_back(tmp);
                tmp = "";
            }
            else
                tmp += str[i];
        }
        str1.push_back(tmp);
        if(len1 != str1.size())
            return false;
        for(int i=0; i<len1; i++){
            if(dic1.find(str1[i]) == dic1.end() && dic2.find(pattern[i]) == dic2.end()){
                dic1[str1[i]] = pattern[i];
                dic2[pattern[i]] = str1[i];
            }
            else if(dic1.find(str1[i]) != dic1.end() && dic1[str1[i]] != pattern[i])
                return false;
            else if(dic2.find(pattern[i]) != dic2.end() && dic2[pattern[i]] != str1[i])
                return false;
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/80705099