LeetCode 97 Interleaving String (C++)

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.


Solution C++


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
struct cachehash {
public:
    size_t operator()(const pair<int, int>& p) const {
        return hash<int>()(p.first) ^ hash<int>()(p.second);
    }
};

class Solution {
    bool intIsInterleave(unordered_map<pair<int, int>, bool, cachehash>& cache, string& s1, int last1, string& s2, int last2, string& s3, int last3) {
        auto it = cache.find({last1, last2});
        if (it != cache.end()) return it->second;
        if (last1 == -1) {
            bool ret = s2.substr(0, last2 + 1) == s3.substr(0, last3 + 1);
            cache[{last1, last2}] = ret;
            return ret;
        }

        if (last2 == -1) {
            bool ret = s1.substr(0, last1 + 1) == s3.substr(0, last3 + 1);
            cache[{last1, last2}] = ret;
            return ret;
        }

        bool ret = false;
        if (s1[last1] == s3[last3]) {
            ret = intIsInterleave(cache, s1, last1 - 1, s2, last2, s3, last3 - 1);
        }

        if (!ret && s2[last2] == s3[last3]) {
            ret = intIsInterleave(cache, s1, last1, s2, last2 - 1, s3, last3 - 1);
        }
        cache[{last1, last2}] = ret;
        return ret;
    }

public:

    bool isInterleave(string s1, string s2, string s3) {
        unordered_map<pair<int,int>, bool, cachehash> cache;
        return intIsInterleave(cache, s1, s1.length() - 1, s2, s2.length() - 1, s3, s3.length() - 1);
    }
};

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving