贝壳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; } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!