acwing139. 回文子串的最大长度

简介: acwing139. 回文子串的最大长度

139. 回文子串的最大长度 - AcWing题库

字符串哈希

这里用到了二分找半径,不知道为什么对二分的理解又远了一步

#include<iostream>
#include<algorithm>
#include<cstring>
 
using namespace std ;
const int N = 2000000 + 10 , P = 131 ;
typedef unsigned long long ULL ;
ULL hl[N] , hr[N] ,p[N];
char a[N] ;
ULL get(ULL h[] ,ULL l ,ULL r){
  return h[r] - h[l-1] * p[r - l + 1] ;
}
int main(){
  int cnt = 1 ;
  while(1){
    
    scanf("%s",a+1) ;
    if(a[1]=='E') break ;
    int n = strlen(a+1) ;
    for(int i = n*2 ; i  ; i -= 2 ){
      a[i] = a[i/2] ;
      a[i-1] = 'a' + 26 ;
    }
    n *= 2 ;
    p[0] = 1 ;
    for(int i = 1 , j = n; i <= n ; i ++ , j -- ){
      hl[i] = hl[i-1] * P + a[i] - 'a' + 1  ;
      hr[i] = hr[i-1] * P + a[j] - 'a' + 1 ;
      p[i] =  p[i-1] *P ;
    }
    int res = 0 ;
    for(int i = 1 ; i <= n ;i  ++){
      int l = 0 , r = min(i-1 , n-i) ;
      while(l < r){
        int mid = r + l + 1 >> 1 ;
        if(get(hl,i-mid,i-1) == get(hr,n - (i + mid) + 1,n - (i+1)+1)) l = mid ;
        else r = mid - 1 ;  
      }
      if(a[i-l] <= 'z') res = max(res,l+1) ;
      else res = max(res,l) ;
    }
    printf("Case %d: %d\n", cnt ++ , res);
  }
  return 0 ;
}
目录
相关文章
|
12天前
acwing 897 最长公共子序列
acwing 897 最长公共子序列
18 0
acwing 897 最长公共子序列
|
4月前
|
Java
5.最长回文子串
5.最长回文子串
|
5月前
leetcode-647:回文子串
leetcode-647:回文子串
32 0
Acwing 3692. 最长连续公共子序列
Acwing 3692. 最长连续公共子序列
62 0
每日一题:Leetcode209 长度最小的子数组
每日一题:Leetcode209 长度最小的子数组
|
Shell Python
LeetCode 821. 字符的最短距离
给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。
111 0
|
算法 Java 索引
最长回文子串
最长回文子串
117 0
最长回文子串
LeetCode——821. 字符的最短距离
LeetCode——821. 字符的最短距离
72 0