<p>Given two strings <code>text1</code> and <code>text2</code>, return <em>the length of their longest <strong>common subsequence</strong>. </em>If there is no <strong>common subsequence</strong>, return <code>0</code>.</p>

<p>A <strong>subsequence</strong> of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.</p>

<ul>
	<li>For example, <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;abcde&quot;</code>.</li>
</ul>

<p>A <strong>common subsequence</strong> of two strings is a subsequence that is common to both strings.</p>

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

<pre>
<strong>Input:</strong> text1 = &quot;abcde&quot;, text2 = &quot;ace&quot; 
<strong>Output:</strong> 3  
<strong>Explanation:</strong> The longest common subsequence is &quot;ace&quot; and its length is 3.
</pre>

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

<pre>
<strong>Input:</strong> text1 = &quot;abc&quot;, text2 = &quot;abc&quot;
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest common subsequence is &quot;abc&quot; and its length is 3.
</pre>

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

<pre>
<strong>Input:</strong> text1 = &quot;abc&quot;, text2 = &quot;def&quot;
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no such common subsequence, so the result is 0.
</pre>

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

<ul>
	<li><code>1 &lt;= text1.length, text2.length &lt;= 1000</code></li>
	<li><code>text1</code> and <code>text2</code> consist of only lowercase English characters.</li>
</ul>

class Solution
{
public:
    int longestCommonSubsequence(const std::string &text1, const std::string &text2)
    {
        uint16_t rows = text1.length() + 1,
                 cols = text2.length() + 1,
                 x, y,
                 acc = 0;

        uint16_t matrix[rows][cols];
        memset(matrix, 0, sizeof(uint16_t) * rows * cols);

        for (y = 1; y < rows; ++y)
            for (x = 1; x < cols; ++x)
                if (text1[y - 1] == text2[x - 1])
                    matrix[y][x] = matrix[y - 1][x - 1] + 1;
                else
                    matrix[y][x] = std::max(matrix[y - 1][x], matrix[y][x - 1]);

        for (y = rows - 1, x = cols - 1; y > 0 && x > 0;)
            if (matrix[y][x] > std::max(matrix[y - 1][x], matrix[y][x - 1]))
                y--, x--, acc++;
            else if (matrix[y][x - 1] > matrix[y - 1][x])
                x--;
            else
                y--;

        return acc;
    }
};
9486