Somebody help me


  • 0
    T

    Why my code cannot run "ab", "ccc"? This case should be true.

    class Solution {
        public:
            bool wordPatternMatch(string pattern, string str) {
                unordered_set<string> set;
                unordered_map<char, string> map;
                
                return backtracking(0, 0, pattern, str, set, map);
            }
        private:
            bool backtracking(int count, int level, string pattern, string str, unordered_set<string> &set, unordered_map<char, string> &map)
            {
                if(level == str.size() && count == pattern.size())
                {
                    return true;
                }
                else if(level == str.size() || count == pattern.size())
                {
                    return false;
                }
                
                for(int i = level; i < str.size(); i++)
                {
                    int flag = 0;
                    string s = str.substr(level, i-level+1);
                    if(map.count(pattern[count]) == 0 && set.count(s) == 0)
                    {
                        map.insert({pattern[count], s});
                        set.insert(s);
                        flag = 1;
                    }
                    else if(map[pattern[count]] != s)
                    {
                        continue;
                    }
                    
                    if(backtracking(count+1, i+1, pattern, str, set, map))
                        return true;
                    
                    if(flag == 1)
                    {
                        map.erase(pattern[count]);
                        set.erase(s);
                    }
                }
                
                return false;
            }
        };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.