<p>Given two integers <code>a</code> and <code>b</code>, return <strong>any</strong> string <code>s</code> such that:</p>

<ul>
	<li><code>s</code> has length <code>a + b</code> and contains exactly <code>a</code> <code>&#39;a&#39;</code> letters, and exactly <code>b</code> <code>&#39;b&#39;</code> letters,</li>
	<li>The substring <code>&#39;aaa&#39;</code> does not occur in <code>s</code>, and</li>
	<li>The substring <code>&#39;bbb&#39;</code> does not occur in <code>s</code>.</li>
</ul>

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

<pre>
<strong>Input:</strong> a = 1, b = 2
<strong>Output:</strong> &quot;abb&quot;
<strong>Explanation:</strong> &quot;abb&quot;, &quot;bab&quot; and &quot;bba&quot; are all correct answers.
</pre>

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

<pre>
<strong>Input:</strong> a = 4, b = 1
<strong>Output:</strong> &quot;aabaa&quot;
</pre>

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

<ul>
	<li><code>0 &lt;= a, b &lt;= 100</code></li>
	<li>It is guaranteed such an <code>s</code> exists for the given <code>a</code> and <code>b</code>.</li>
</ul>

#include <queue>
#include <string>
using namespace std;

class Solution {
public:
    string strWithout3a3b(int a, int b) {
        // Priority queue to store pairs of (count, character), with the character that has more remaining count on top.
        priority_queue<pair<int, char>> pq;
        string ans = "";

        // Push initial counts into the priority queue.
        if (a > 0) pq.push({a, 'a'});
        if (b > 0) pq.push({b, 'b'});

        while (!pq.empty()) {
            // Take the character with the highest count.
            auto [count1, ch1] = pq.top();
            pq.pop();

            // Add the character to the answer string.
            if (ans.size() >= 2 && ans.back() == ch1 && ans[ans.size() - 2] == ch1) {
                // If the last two characters are the same as ch1, we need to take the next character (if it exists).
                if (pq.empty()) break;  // No other character to choose, so we're done.

                auto [count2, ch2] = pq.top();
                pq.pop();

                // Use ch2 instead to avoid three consecutive same characters.
                ans += ch2;
                count2--;

                // Reinsert ch2 back if there's still some left.
                if (count2 > 0) pq.push({count2, ch2});

                // Push ch1 back as it wasn't used.
                pq.push({count1, ch1});
            } else {
                // Safe to add ch1 without violating the three consecutive rule.
                ans += ch1;
                count1--;

                // Reinsert ch1 if there's any count left.
                if (count1 > 0) pq.push({count1, ch1});
            }
        }

        return ans;
    }
};

8100