OJ模板库

近期刷了好几次的oj,好受伤好多都是相似的题目。

最长回文子串

string preprocess(string &str)
{
    string afterProcessStr="#";
    for(int i=0;i<str.size();++i)
    {
        afterProcessStr += str.substr(i, 1)+"#";
    }
    return afterProcessStr;
    //afterProcessStr.clear();
}
int maxpalindrome(string &str)
{
   string afterProcessStr=preprocess(str);
  // cout<<afterProcessStr<<endl;
   int maxEdge=0,center=0;
   int *p=new int[afterProcessStr.size()]();
   int ans=0;
   int cur=0;
   for(int i=1;i<afterProcessStr.size();++i)
   {
       p[i]=(maxEdge>i)?min(maxEdge-i,p[2*center-i]):0;
       while(i-1-p[i]>=0&&i+1+p[i]<afterProcessStr.size()&&afterProcessStr[i+1+p[i]]==afterProcessStr[i-1-p[i]])
          ++p[i];
          if(i+p[i]>maxEdge)
          {
              center=i;
              maxEdge=i+p[i];
          }
          if(p[i]>ans)
           ans=p[i];

   }
    return ans;
}

注意上文中preprocess函数会花费大量时间最好是採用预分配内存。

static string afterProcessStr(1000002*2,'#');

详细见:http://blog.csdn.net/zhouyelihua/article/details/46964175

最大公约数

常常使用的最大公约数的方法有辗转相除法

/*
输入x,y
返回x,y的最大公约数
*/
int gcd(int x,int y)
{
if(x<y)
  return gcd(y,x);
if(0==y)
    return x;
else
{
    if(0==x&0x1)
    {
        if(0==y&0x01)
            return (gcd(x>>1,y>>1)<<1);
        else
            return gcd(x>>1,y);
    }
    else
    {
      if(0==y&0x01)
            return gcd(x,y>>1);
        else
            return gcd(y,x-y);
    }
}
}
posted @ 2018-04-20 20:22  zhchoutai  阅读(182)  评论(0编辑  收藏  举报