码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Word Pattern II"

时间:2015-10-10 15:20:36      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

Here is the mind flow: we don‘t know 1st token right? then we try it one by one - recursively.

技术分享
typedef unordered_map<string, string> HMap;
class Solution {
    bool go(string pattern, string str, HMap p2s)
    {
        size_t plen = pattern.length();
        size_t slen = str.length();
        if(!plen) return !slen;
        if(plen > slen) return false;

        string c = pattern.substr(0, 1);
        string npat = pattern.substr(1);
        for(int sl = 1; sl <= slen; sl ++)
        {
            string tk = str.substr(0, sl);
            string nstr = str.substr(sl);
            if(p2s.count(c))
            {
                if(p2s[c] == tk)
                {
                    if(go(npat, nstr, p2s))
                        return true;
                }
            }
            else
            {
                HMap np2s = p2s;
                np2s[c] = tk;
                if(go(npat, nstr, np2s))
                    return true;
            }
        }
        return false;
    }
public:
    bool wordPatternMatch(string pattern, string str) {
        size_t plen = pattern.length();
        size_t slen = str.length();
        if(plen == 0) return slen == 0;
        if(plen == 1) return slen > 0;
        if(plen > slen) return false;

        string c = pattern.substr(0, 1);
        string npat = pattern.substr(1);

        for(int sl = 1; sl <= slen; sl ++)
        {
            string head = str.substr(0, sl);
            HMap p2s; p2s[c] = head;

            string nstr = str.substr(sl);
            if(go(npat, nstr, p2s))
                return true;
        }
        return false;
    }
};
View Code

LeetCode "Word Pattern II"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4866844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!