AcWing 139. 【java】回文子串的最大长度
原题链接
中等
作者:
tt2767
,
2019-12-17 00:55:21
,
所有人可见
,
阅读 921
import java.util.*;
public class Main{
void run(){
List<String> str = new ArrayList<>();
power.add(1L);
while (true){
String s = jin.next();
if (s.equals("END")) break;
str.add(s);
}
solve(str);
}
void solve(List<String> strs){
for (int i = 0 ; i < strs.size(); i++) System.out.printf("Case %d: %d\n", i+1, calc(strs.get(i)));
}
int calc(String str){
buffer.setLength(0);
char[] s = str.toCharArray();
for (int i = 0 ; i < str.length(); i++){
buffer.append(s[i]);
buffer.append('{');
}
buffer.setLength(buffer.length()-1);
String newStr = buffer.toString();
long[] hashs = hashCode(newStr);
String rNewStr = new StringBuilder(newStr).reverse().toString();
long[] rhashs = hashCode(rNewStr);
char[] string = newStr.toCharArray();
int res = 0;
for (int i = 1 ; i <= string.length; i++){
int l = 0;
int r = Math.min(i - 1, string.length - i);
while (l < r){
int mid = ( l + r + 1) >> 1;
long phash = getHash(hashs, i - mid , i - 1);
long rhash = getHash(rhashs,string.length- (i+mid)+1, string.length-(i+1)+1);
if (phash != rhash) r = mid - 1;
else l = mid;
}
int ans = string[i-l-1] == '{' ? l : l+1; // 开始没理解好,这里应该是i-l-1而不是i-1,要判断起点才可以,而不能判断中间点,中间点无法确定谁多
res = Math.max(res, ans);
}
return res;
}
long[] hashCode(String string){
char[] str = string.toCharArray();
long[] hashs = new long[str.length+1];
for (int i = 1 ; i <= str.length ; i++){
hashs[i] = (hashs[i-1] * base + str[i-1]-'a'+1) % Long.MAX_VALUE;
if (i >= power.size()) power.add(power.get(power.size()-1) * base);
}
return hashs;
}
long getHash(long[] hashs, int l, int r){
return hashs[r] - hashs[l-1] * power.get(r - l + 1);
}
private List<Long> power = new ArrayList<>();
private int base = 131;
private StringBuilder buffer = new StringBuilder();
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception {new Main().run();}
}