解法一:动态规划

参考官方题解:https://leetcode-cn.com/problems/UlBDOe/solution/qiu-xie-shou-cang-ji-by-leetcode-solution/

  1. class Solution {
  2. public int minimumOperations(String leaves) {
  3. int n = leaves.length();
  4. int[][] dp = new int[n][3];
  5. dp[0][0] = toRed(leaves.charAt(0));
  6. dp[0][1] = dp[0][2] = dp[1][2] = Integer.MAX_VALUE;
  7. for (int i = 1; i < n; ++i) {
  8. dp[i][0] = dp[i - 1][0] + toRed(leaves.charAt(i));
  9. dp[i][1] = Math.min(dp[i - 1][0], dp[i - 1][1]) + toYellow(leaves.charAt(i));
  10. if (i >= 2) {
  11. dp[i][2] = Math.min(dp[i - 1][1], dp[i - 1][2]) + toRed(leaves.charAt(i));
  12. }
  13. }
  14. return dp[n - 1][2];
  15. }
  16. private int toRed(char ch) {
  17. if (ch == 'r') {
  18. return 0;
  19. } else {
  20. return 1;
  21. }
  22. }
  23. private int toYellow(char ch) {
  24. if (ch == 'y') {
  25. return 0;
  26. } else {
  27. return 1;
  28. }
  29. }
  30. }