子串分值(Java)
分析
每个字母的贡献 = (该字母当前的位置 - 上一次出现的位置)* (下一次出现的位置 - 该字母当前的位置)
子串分值 = 各个位置字母的贡献之和
问就是我也想不到这个方法😭
但是,按我的理解这个公式是这样的:
话不多说上代码
public class Main{
//记录上一个出现的位置
static int pre[];
//记录下一个出现的位置
static int next[];
//记录字母“当前”的位置
static int al[] = new int [26];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inp = sc.next();
pre = new int[inp.length()+1];
next = new int[inp.length()+1];
//初始化al,假设字母最初始出现的位置为-1
Arrays.fill(al, -1);
//记录每个位置的字母出现的前一个位置
for(int i = 0; i < inp.length(); i++){
int t = (int)inp.charAt(i) - 'a';
pre[i] = al[t];
al[t] = i;
}
//假设字母最后出现的位置为inp.length()
Arrays.fill(al, inp.length());
//记录每个位置的字母出现的下一个位置
for(int i = inp.length() - 1; i >= 0; i--){
int t = (int)inp.charAt(i) - 'a';
next[i] = al[t];
al[t] = i;
}
long sum = 0;
for(int i = 0; i < inp.length(); i++){
sum += (i - pre[i]) * (next[i] - i);
}
System.out.println(sum);
}
}