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 ;
}
目录
打赏
0
0
0
0
24
分享
相关文章
【Leetcode-13.罗马数字转整数 -14.最长公共前缀】
【Leetcode-13.罗马数字转整数 -14.最长公共前缀】
77 0
【Leetcode -231. 2的幂 -242.有效的字母异位词 -258.各位相加】
【Leetcode -231. 2的幂 -242.有效的字母异位词 -258.各位相加】
51 0
|
11月前
leetcode-647:回文子串
leetcode-647:回文子串
52 0
|
11月前
|
Leetcode算法系列| 12. 整数转罗马数字
Leetcode算法系列| 12. 整数转罗马数字
[LeetCode] 无重复字符的最长子串 & 最长回文子串
博主最近在看新的工作机会,也是在找一些leetcode上比较高频的算法复习一下,这里分享两道算法题的解题。
79 2
[LeetCode] 无重复字符的最长子串 & 最长回文子串
leetcode刷题记录:7.整数反转,8.字符串转整数,9.回文数
leetcode刷题记录:7.整数反转,8.字符串转整数,9.回文数
92 0
Leetcode 647 回文子串
Leetcode 647 回文子串
110 0
leetcode 647 回文子串
leetcode 647 回文子串
132 0
leetcode 647 回文子串
力扣刷题记录——231. 2 的幂、228. 汇总区间、242. 有效的字母异位词
力扣刷题记录——231. 2 的幂、228. 汇总区间、242. 有效的字母异位词
122 0
力扣刷题记录——231. 2 的幂、228. 汇总区间、242. 有效的字母异位词
LeetCode(1-两数之和&&2-两数相加&&3-无重复字符的最长子串)
LeetCode(1-两数之和&&2-两数相加&&3-无重复字符的最长子串)
LeetCode(1-两数之和&&2-两数相加&&3-无重复字符的最长子串)