বৃহস্পতিবার, ২৬ মার্চ, ২০২০

11475 Extend to Palindrome By Using KMP algo

#include <bits/stdc++.h>
using namespace std;
int b[300010];
void kmpPreprocess(string P, int m)
{
    int i = 0, j = -1;
    b[0] = -1;
    while (i < m)
    {
        while (j >= 0 && P[i] != P[j])
        {
            j = b[j];
        }
        i++;
        j++;
        b[i] = j;
    }
}
int main()
{
string s,ss;
while(cin>>s)
{
int x=s.size();
        ss=s;
        reverse(s.begin(),s.end());
        s=s+"~"+ss;
        int m=s.size();
        kmpPreprocess(s, m);
        for(int i=b[m-1]+1;i<x;i++)
            ss+=s[i];
        cout<<ss<<endl;
}
    return 0;
}

UVA 455 Periodic Strings by using Z algo

#include <bits/stdc++.h>
using namespace std;
vector<int> ans;
int z[500];
void Z_algo(string s)
{
    int n = s.length();
    z[0] = 0;
    for(int i = 1, l = 0, r = 0;i<n;i++)
    {
        if(i<=r) z[i] = min(r-i+1, z[i-l]);
        else z[i] = 0;
        while(z[i]+i<n && s[z[i]]==s[z[i]+i]) ++z[i];
        if(z[i]+i-1>r) l = i, r = z[i]+i-1;
    }
}
int main()
{
int ts,cs=1;
cin>>ts;
while(ts--)
{
if(cs>1)
cout<<endl;
cs++;
    string s;
    cin>>s;
        Z_algo(s);
        int n = s.length();
        int mx = n;
for (int i = 1; i < n; ++i)
{
if (n % i == 0 and z[i] + i == n)
{
mx = i;
break;
}
}
cout<<mx<<endl;
        memset(z,0,sizeof(z));
    }
    return 0;
}

Factory Pattern

Factory Method  is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alte...