【LeetCode】290. Word Pattern 解题小结

题目:

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.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

采取的办法是建立两个map,相互映射。为什么用一个map不够?如果面对第4个例子,abba,dog dog dog dog,a和b都会映射到dog,因为你要保证1对1映射,那么可以采取反面映射过来。

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        unordered_map<char, string> dictP;
        unordered_map<string, char> dictS;
        string buff;
        int idx = 0;
        for (int i = 0; i < pattern.size(); i++){
            buff.clear();
            while (idx < str.size() && str[idx] != ' '){
                buff.push_back(str[idx++]);
            }
            if (buff.empty()) return false;
            idx++;
            
            if (dictP.find(pattern[i]) == dictP.end() && dictS.find(buff) == dictS.end()){
                dictP[pattern[i]] = buff;
                dictS[buff] = pattern[i];
            }
            else if (dictP[pattern[i]] != buff || dictS[buff] != pattern[i]) 
                return false;
        }
        if (idx == 0 || idx < str.size())
            return false;
        return true;
    }
};

 

posted on 2016-08-31 10:14  医生工程师  阅读(169)  评论(0编辑  收藏  举报

导航