标签:
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; } };
标签:
原文地址:http://www.cnblogs.com/tonix/p/4866844.html