<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code><em> if </em><code>s2</code><em> contains a permutation of </em><code>s1</code><em>, or </em><code>false</code><em> otherwise</em>.</p>

<p>In other words, return <code>true</code> if one of <code>s1</code>&#39;s permutations is the substring of <code>s2</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s1 = &quot;ab&quot;, s2 = &quot;eidbaooo&quot;
<strong>Output:</strong> true
<strong>Explanation:</strong> s2 contains one permutation of s1 (&quot;ba&quot;).
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s1 = &quot;ab&quot;, s2 = &quot;eidboaoo&quot;
<strong>Output:</strong> false
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s1.length, s2.length &lt;= 10<sup>4</sup></code></li>
	<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
</ul>

class Solution {
public:
    bool checkInclusion(string s1, string s2) {
        unordered_map<char, int> a2i;
        for (int i = 0; i < s1.length(); i++) {
            a2i[s1[i]]++;
        }
        /*
        for (const auto& ele : a2i) {
            cout << "key: " << ele.first << ", val: " << ele.second << endl;
        }*/
        int l = 0;
        int r = 0;
        int N = s2.length();
        unordered_map<char, int> a2i_copy = a2i;
        while (l <= r && r < N) {
            // cout << "l = " << l << ", r = " << r << endl;
            if (!Contains(a2i, s2[r])) {
                l = r+1;
                a2i = a2i_copy;
                // r++;
            } else {
                // cout << "a2i[" << s2[r] << "] = " << a2i[s2[r]] << endl;
                if (a2i[s2[r]] > 0) {
                    // We had the necessary resource.
                    a2i[s2[r]]--;
                    if (r-l+1 == s1.length()) {
                        return true;
                    }
                    // r++;
                } else {
                    while (l < N && s2[l] != s2[r]) {
                        a2i[s2[l]]++;
                        l++;
                    }
                    if (l == N) {
                        return false;
                    }
                    // a2i[s2[l]]--;
                    l++;
                    // a2i[s2[r]]++;;
                    if (r-l+1 == s1.length()) {
                        return true;
                    }
                    // r++;
                }
            }
            r++;
        }
        return false;
    }
private:
    // Returns true if char x is present inside the map a2i.
    bool Contains(unordered_map<char, int> a2i, char x) {
        if (a2i.find(x) == a2i.end()) {
            return false;
        } else {
            return true;
        }
    }
};
128378