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.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int i = 0;
        istringstream stream(str);
        unordered_map<char, string> chtostr;
        unordered_map<string, char> strtoch;
        string word;
        vector<string> str2;
        while (stream >> word)
            str2.push_back(word);
        if (pattern.size() != str2.size())
            return false;
        for (; i < pattern.size(); i++)
        {
            auto findPtr = chtostr.find(pattern[i]);
            if (findPtr != chtostr.cend())
            {
                if (findPtr->second != str2[i])
                    return false;
            }
            else
                chtostr.insert({ pattern[i], str2[i] });
        }
        i = 0;
        for (; i < str2.size(); i++)
        {
            auto findPtr = strtoch.find(str2[i]);
            if (findPtr != strtoch.cend())
            {
                if (findPtr->second != pattern[i])
                    return false;
            }
            else
                strtoch.insert({str2[i], pattern[i]});
        }
        return true;
    }
};
  • 和之前做的是一样的,建立两个对应表,然后对照下是否一样
  • map的find返回的是一个pair的迭代器,第一个是key,第二个是值
posted @ 2015-10-17 11:31  dylqt  阅读(149)  评论(0编辑  收藏  举报