买卖股票的最好时机(二)&&通配符匹配&&二叉树的镜像

147 阅读1分钟

NC134 买卖股票的最好时机(二)

题目链接

1、解题思路

一维dp,可以把空间压缩到O(1)的空间。

2、代码
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 计算最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        int sum = 0;
        if (prices == null || prices.length <= 1) {
            return 0;
        }
        int before = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > before) {
                sum = sum + prices[i] - before;
                before = prices[i];
            } else {
                before = prices[i];
            }
        }
        return sum;
    }
}

NC44 通配符匹配

题目链接

1、解题思路

二维dp,模拟就好。

2、代码
public class Solution {
    public boolean isMatch(String s, String p) {
        boolean[][] dp = new boolean[1005][1005];
        dp[0][0] = true;
        for (int i = 1; i <= p.length(); i++) {
            if (p.charAt(i - 1) == '*') {
                dp[0][i] = true;
            } else {
                break;
            }
        }
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= p.length(); j++) {
                if (p.charAt(j - 1) == '*') {
                    dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
                } else if (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                }
            }
        }
        return dp[s.length()][p.length()];
    }
}

NC72 二叉树的镜像

题目链接

1、解题思路

递归的思路,在修改左子树的时候注意提前处理左子树并保存。

2、代码
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    public TreeNode Mirror (TreeNode pRoot) {
        if (pRoot == null) {
            return null;
        } else {
            TreeNode temp = Mirror(pRoot.left);
            pRoot.left = Mirror(pRoot.right);
            pRoot.right = temp;
            return pRoot;
        }
    }
}