解法一:动态规划
参考官方题解:https://leetcode-cn.com/problems/UlBDOe/solution/qiu-xie-shou-cang-ji-by-leetcode-solution/
class Solution {
public int minimumOperations(String leaves) {
int n = leaves.length();
int[][] dp = new int[n][3];
dp[0][0] = toRed(leaves.charAt(0));
dp[0][1] = dp[0][2] = dp[1][2] = Integer.MAX_VALUE;
for (int i = 1; i < n; ++i) {
dp[i][0] = dp[i - 1][0] + toRed(leaves.charAt(i));
dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][1]) + toYellow(leaves.charAt(i));
if (i >= 2) {
dp[i][2] = Math.min(dp[i - 1][1], dp[i - 1][2]) + toRed(leaves.charAt(i));
}
}
return dp[n - 1][2];
}
private int toRed(char ch) {
if (ch == 'r') {
return 0;
} else {
return 1;
}
}
private int toYellow(char ch) {
if (ch == 'y') {
return 0;
} else {
return 1;
}
}
}