红和绿
用动态规划
dp保存当前位置所要涂色的最小次数
每到一个新的位置,要么给它变色,要么把它前面的所有绿色变为红色。所以每个位置都比较一次前面绿色的个数,和前一位变色的总位置之间的最小的值
import java.util.*; public class Main { public static int RG(String str) { int n=str.length(); int[] dp=new int[n];//到当前位置的最小涂色次数 int gCount=0; if(str.charAt(0)=='G') gCount++; for(int i=1;i<n;i++) { if(str.charAt(i)=='R') { dp[i]=Math.min(dp[i-1]+1, gCount); } else { dp[i]=dp[i-1]; gCount++; } } return dp[n-1]; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str=scan.nextLine(); System.out.println(Main.RG(str)); } }
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/10862485.html

浙公网安备 33010602011771号