蓝桥杯 15决赛 A5 切开字符串(String操作)
Pear有一个字符串,不过他希望把它切成两段。
这是一个长度为N(<=10^5)的字符串。
Pear希望选择一个位置,把字符串不重复不遗漏地切成两段,长度分别是t和N-t(这两段都必须非空)。
Pear用如下方式评估切割的方案:
定义“正回文子串”为:长度为奇数的回文子串。
设切成的两段字符串中,前一段中有A个不相同的正回文子串,后一段中有B个不相同的非正回文子串,则该方案的得分为AB。
注意,后一段中的B表示的是:“…非正回文…”,而不是: “…正回文…”。
那么所有的切割方案中,AB的最大值是多少呢?
【输入数据】
输入第一行一个正整数N(<=10^5)
接下来一行一个字符串,长度为N。该字符串仅包含小写英文字母。
【输出数据】
一行一个正整数,表示所求的A*B的最大值。
【样例输入】
10
bbaaabcaba
【样例输出】
38
【数据范围】
对于20%的数据,N<=100
对于40%的数据,N<=1000
对于100%的数据,N<=10^5
资源约定:
峰值内存消耗(含虚拟机) < 512M
CPU消耗 < 2000ms
=========================================
思路:
先找出正回文串(余下来的自然就是 非…)
遍历原串的上下限坐标,得到可能的字串
set去重
package cn.蓝桥.决赛15.A;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/*
@author weng
@build 2020年7月21日 下午2:06:59
*/
public class 思路_切开字符串_5 {
static int n;
static char[] c;
static String s;
static boolean[][] isHui;
static int ans;
static Set<String> set;
static long t;
public static void main(String[] args) {
init();
// t =System.currentTimeMillis();
//标记所有 正回文
for(int i =0 ;i <n ;i ++) {//字串上限
isHui[i][i +1] =true;
for(int j =i +3 ;j <=n ;j +=2) if(checkHui(i ,j)) isHui[i][j] =true;//子串下限
}
//分割点
for(int i =1 ;i <n ;i ++) {
aly(i);
}
System.out.println(ans);
// System.out.println(System.currentTimeMillis() -t);
}
private static void aly(int spl) {
int a =0 ,b =0;
set =new HashSet<String>();
//统计A个不相同的正回文子串
for(int i =0 ;i <spl ;i ++) {//左侧上限
for(int j =i +1 ;j <=spl ;j +=2) {//左侧下限
if(isHui[i][j]) {
if(set.add(s.substring(i ,j))) a ++;
}
}
}
set.clear();
//B个不相同的非正回文子串
for(int i =spl ;i <n ;i ++) {
for(int j =i +2 ;j <=n ;j ++) {
if(!isHui[i][j]) {
if(set.add(s.substring(i ,j))) b ++;
}
}
}
if(ans <a *b) ans =a *b;
}
private static boolean checkHui(int sta, int end) {
end --; //为配合substring[)区间的右侧+1,因此这里给-1
for(int i =0 ;i <(end -sta) /2 ;i ++) {
if(c[sta +i] !=c[end -i]) return false;
}
return true;
}
private static void init() {
Scanner sc = new Scanner(System.in);
n =sc.nextInt();
s =sc.next().trim();
c =s.toCharArray();
isHui =new boolean[n][n +1];
sc.close();
}
}
``