小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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:
pattern = “abba”, str = “dog cat cat dog” should return true.
pattern = “abba”, str = “dog cat cat fish” should return false.
pattern = “aaaa”, str = “dog cat cat dog” should return false.
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.

分析

字符串的模式匹配,类似于离散数学中的双向映射问题。

利用unordered_map数据结构建立双向映射,逐个判断匹配。

AC代码

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        if (str.empty())
            return false;

        //从输入的字符串源串得到字符串数组
        vector<string> strs;
        string s = "";
        for (int i = 0; str[i] != '\0'; ++i)
        {
            if (str[i] == ' ')
            {
                strs.push_back(s);
                s = "";
            }
            else
                s += str[i];
        }//for
        //保存末尾单词
        strs.push_back(s);

        if (pattern.size() != strs.size())
            return false;
        //判断模式匹配
        int len = pattern.size();
        unordered_map<char, string> um1;
        unordered_map<string, char> um2;
        for (int i = 0; i < len; ++i)
        {
            auto iter1 = um1.find(pattern[i]);
            auto iter2 = um2.find(strs[i]);

            if (iter1 != um1.end() && iter2 != um2.end())
            {
                if ((*iter1).second == strs[i] && (*iter2).second == pattern[i])
                    continue;
                else
                    return false;
            }//if
            else if (iter1 == um1.end() && iter2 != um2.end())
                return false;
            else if (iter1 != um1.end() && iter2 == um2.end())
                return false;
            else
                um1.insert({ pattern[i], strs[i] });
                um2.insert({ strs[i], pattern[i] });
        }//for
        return true;
    }
};

GitHub测试程序源码

posted on 2015-11-23 13:33  Coding菌  阅读(151)  评论(0编辑  收藏  举报