<p>Given two strings <code>a</code> and <code>b</code>, return <em>the minimum number of times you should repeat string </em><code>a</code><em> so that string</em> <code>b</code> <em>is a substring of it</em>. If it is impossible for <code>b</code>​​​​​​ to be a substring of <code>a</code> after repeating it, return <code>-1</code>.</p>

<p><strong>Notice:</strong> string <code>&quot;abc&quot;</code> repeated 0 times is <code>&quot;&quot;</code>, repeated 1 time is <code>&quot;abc&quot;</code> and repeated 2 times is <code>&quot;abcabc&quot;</code>.</p>

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

<pre>
<strong>Input:</strong> a = &quot;abcd&quot;, b = &quot;cdabcdab&quot;
<strong>Output:</strong> 3
<strong>Explanation:</strong> We return 3 because by repeating a three times &quot;ab<strong>cdabcdab</strong>cd&quot;, b is a substring of it.
</pre>

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

<pre>
<strong>Input:</strong> a = &quot;a&quot;, b = &quot;aa&quot;
<strong>Output:</strong> 2
</pre>

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

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

class Solution {
public:
    int repeatedStringMatch(string a, string b) {
        int na = a.size();
        int nb = b.size();
        if(a == b) return 1;
        if(nb > na)
        {
            for(int i=0;i<nb-na;i++)
                if(b[i] != b[i+na]) return -1;
        }
        int repeat;
        bool flag = false;
        if(nb <= na) repeat = nb;
        else repeat = na;
        string comp_b = b.substr(0,repeat);
        string comp_a = a.substr(0,repeat);
        if(comp_a == comp_b)
        {
            int ans;
            if(nb <= na) ans=1;
            else
            {
                if(nb%repeat == 0) ans = nb/repeat;
                else ans = nb/repeat+1;
            }
            return ans;
        }
        int end_ind = repeat-1, i;
        //cout<<comp_a<<" "<<comp_b;
        for(i=1;i<na;i++)
        {
            end_ind++;
            if(end_ind == na) end_ind = 0;
            comp_a.push_back(a[end_ind]);
            comp_a = comp_a.substr(1,repeat);
            //cout<<comp_a<<"\n"<<comp_b<<"\n";
            if(comp_a == comp_b)
            {
                break;
            }
        }
        if(i == na) return -1; 
        int ans;
        if(nb <= na)
        {
            if(end_ind < i) 
                ans = 2;
            else
                ans = 1;
        }
        else
        {
            int rem = nb%repeat;
            if(na-i < rem)
                ans = nb/repeat + 2;
            else
                ans = nb/repeat + 1;
        }
        return ans;
    }
};
175380