贝壳3.21

一个字符串可以划分为多个若干的子串,求所有子串的贡献和。子串的贡献可以表示:对于偶数个的字母,贡献为1,对于奇数个的字母,贡献为-1;

eg. 子串cbb的贡献为-1 + 1 = 0

import java.util.Arrays;
import java.util.Scanner;

// 动态规划
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        String str = in.nextLine();
        // dp[i] 表示0,...,i能得到的最大贡献
        // dp[i] = d[j] + score(j, i)  0 =< j <= i
        int[] dp = new int[n];
        Arrays.fill(dp, Integer.MIN_VALUE);
        dp[0] = -1;
        for (int i = 1; i < n; i++) {
            int score = dp[i-1] - 1;    // 初始贡献
            int[] cnt = new int[26];
            for (int j = i; j >= 0; j--) {
                cnt[str.charAt(j) - 'a']++;
                int sc = cal(cnt);
                if (j > 0) {
                    score = Math.max(score, sc + dp[j-1]);
                } else {
                    score = Math.max(score, sc);
                }
            }
            dp[i] = score;
        }
        System.out.println(dp[n-1]);
    }

    public static int cal(int[] cnt) {
        int score = 0;
        for (int x: cnt) {
            if (x == 0) continue;
            if (x % 2 == 1) score--;
            else score++;
        }
        return score;
    }
}

 

posted @ 2022-03-21 23:09  Peterxiazhen  阅读(24)  评论(0编辑  收藏  举报