<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) {
        string s=a;
        int c=1;
        while(a.length()<b.length()){
            a+=s;
            c++;
        }
        if(a==b)return c;
        // cout<<a<<endl;
        vector<long long>pwr(300000,1);
        long long mod=1e9+7;
        long long p=31;
        for(int i=1;i<pwr.size();i++){
            pwr[i]=(pwr[i-1]*p)%mod;
        }
        vector<long long>hash(a.length());
        hash[0]=(a[0]-'a')+1;
        for(int i=1;i<a.length();i++){
            hash[i]=(hash[i-1]+pwr[i]*(long long)(a[i]-'a'+1)+mod)%mod;
        }
        long long bhash=0;
        for(int i=0;i<b.length();i++){
            bhash=(bhash+(b[i]-'a'+1)*pwr[i])%mod;
        }
        if(a.substr(0,b.length())==b)return c;
         for(int i=1;i<a.length()-b.length()+1;i++){
                long long z=hash[i+b.length()-1]-hash[i-1];
                long long tmp=(bhash*pwr[i])%mod;
                if(z==tmp)return c;

            }
            long long z=a.length();
        while(a.length()<=3*z){
              long long cnt=a.length();
            for(int i=0;i<s.length();i++){
                hash.push_back((hash.back()+mod+(s[i]-'a'+1)*pwr[cnt])%mod);
                cnt++;
                a.push_back(s[i]);
            }
            c++;
            if(a.substr(0,b.length())==b)return c;
            // cout<<a<<endl;
            for(int i=a.length()-s.length()-b.length()+1;i<a.length()-b.length()+1;i++){
                long long z=hash[i+b.length()-1]-hash[i-1];
                long long tmp=(bhash*pwr[i])%mod;
                if(z==tmp)return c;

            }
          
        }
        return -1;
    }
};
253431