小美的01串翻转(美团2024届秋招笔试第二场编程真题)
题面

核心思想
区间DP
dp[i][j][2] 表示区间 i~j (i,j都包含)区间 在下标j 变成0 和 1 的 两种情况下满足条件的操作次数
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
final long MOD = (long) (1e9 + 7);
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
int n = s.length();
int[][][] dp = new int[n][n][2];
for(int i = 0; i < n; i++){
dp[i][i][(s.charAt(i)- '0' ) ^ 1] = 1; // 取反操作 +1
}
int res = 0;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(s.charAt(j) == '0'){
dp[i][j][0] = dp[i][j - 1][1]; // 当前保持0 那么前一个就必须是1
dp[i][j][1] = dp[i][j - 1][0] + 1;
}
else{
dp[i][j][1] = dp[i][j - 1][0];
dp[i][j][0] = dp[i][j - 1][1] + 1;
}
res += Math.min(dp[i][j][0], dp[i][j][1]); // 操作最小次数
}
}
System.out.println(res);
}
}

浙公网安备 33010602011771号