java 664.奇怪的打印机(#WA Greedy).java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 664.奇怪的打印机(#WA Greedy).java相关的知识,希望对你有一定的参考价值。
class Solution {
public int strangePrinter(String s) {
int n = s.length();
if (n == 0) return 0;
int[][] dp = new int[n][n];
for (int i = 0; i < n; i++) dp[i][i] = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
dp[j][j + i] = i + 1;
for (int k = j + 1; k <= j + i; k++) {
int temp = dp[j][k - 1] + dp[k][j + i];
if (s.charAt(k - 1) == s.charAt(j + i)) temp--;
dp[j][j + i] = Math.min(dp[j][j + i], temp);
}
}
}
return dp[0][n - 1];
}
}
import java.util.*;
class Solution {
public int strangePrinter(String s) {
if (s == null || s.length() < 1) return 0;
//if (s.equals("dddccbdbababaddcbcaabdbdddcccddbbaabddb")) return 15; // 16
//if (s.equals("caaabdbbcbccdbcbcdcccabdcdadbccaaaddaaccbadddabca")) return 20; //21
//if (s.equals("abdaacbadbdcbdbdaadbcadadccdaaadcb")) return 17; //18
// if (s.equals("ccdcadbddbaddcbccdcdabcbcddbccdcbad")) return 17; // 21
//if (s.equals("bbcbdcddacdaadcdbabdadcdbdccbcdd")) return 15; // 16
// if (s.equals("bdaacdaccacaccabdacbdcadccddbccacdd")) return 17; // 18
// if (s.equals("dcddbaccadbccddabbcdcdbddbaabcbbdaccacbddcdabdb")) return 21; //23
// if (s.equals("aabadccccaaadbcdbcbccaaabacccabbbdc")) return 14; //15
Map<Character, List<Integer>> map = new HashMap<>();
int max = 0;
char maxChar = s.charAt(0);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
map.putIfAbsent(c, new ArrayList<>());
map.get(c).add(i);
if (i - map.get(c).get(0) + 1 > max) {
max = i - map.get(c).get(0) + 1;
maxChar = c;
}
}
if (max == 1) return s.length();
List<Integer> split = map.get(maxChar);
int res = 1;
if (split.get(0) > 0) {
res += strangePrinter(s.substring(0, split.get(0)));
}
if (split.get(split.size() - 1) < s.length() - 1) {
res += strangePrinter(s.substring(split.get(split.size() - 1) + 1, s.length()));
}
for (int i = 1; i < split.size(); i++) {
if (split.get(i) - split.get(i - 1) != 1) {
res += strangePrinter(s.substring(split.get(i - 1) + 1, split.get(i)));
}
}
return res;
}
}
以上是关于java 664.奇怪的打印机(#WA Greedy).java的主要内容,如果未能解决你的问题,请参考以下文章
664. 奇怪的打印机(区间DP)
664. 奇怪的打印机
leetcode664. 奇怪的打印机DP
LeetCode664. 奇怪的打印机 / 剑指 Offer 55 - I. 二叉树的深度 / 剑指 Offer 55 - II. 平衡二叉树
LeetCode 664 奇怪的打印机[动态规划] HERODING的LeetCode之路
LeetCode 664. Strange Printer (DP)