第十周题解

44. 通配符匹配

class Solution {
    public boolean isMatch(String s, String p) {
        int s_index = 0, p_index = 0, sstart = -1, pstart = -1;
		//null与空字符串主要区别如下:
		//null不指向任何对象,相当于没有任何值;而“”代表一个长度为0的字符串
        //null不分配内存空间;而“”会分配内存空间
        if ((p == null || p.isEmpty()) && (s == null || s.isEmpty()))
            return true;

        //遍历s, 判断s的所有字符是否匹配
        while (s_index < s.length()){
            //如果p还没有完,并且s和p的当前字符匹配(结束*匹配字符),就继续判断下一个字符
            if (p_index < p.length() && (s.charAt(s_index) == p.charAt(p_index) || p.charAt(p_index) == '?')){
                s_index ++;
                p_index ++;
            }else if (p_index < p.length() && p.charAt(p_index) == '*'){
                //如果p为*,记录下此时p和s的下标
                sstart = s_index;
                pstart = p_index ++;
            }else if (sstart > -1){
                //如果遇到s.charAt(s_index) == p.charAt(p_index)但是后面又不匹配了,就将sstart继续赋值给s_index
                s_index = ++ sstart;
                //p_index一直指向*后面的那个字符,直到*不再匹配
                //如果遇到s.charAt(s_index) == p.charAt(p_index)但是后面又不匹配了,就将p_index重新指向*后面的那个字符,当作前面的部分也是*匹配的
                p_index = pstart + 1;
            }else {
                return false;
            }
        }
        //s中的字符都判断完毕,则认为s为空,此时需要p为空或者p中只剩下星号的时候,才能成功匹配。
        //如果p中剩余的都是*,则可以移除剩余的*
        while (p_index < p.length() && p.charAt(p_index) == '*')
            p_index ++;
        return p_index == p.length();
    }
}

104. 二叉树的最大深度

解法一:
递归

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null)
            return 0;
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return Math.max(left, right) + 1;
    }
}

解法二:
广度优先搜素

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null)
            return 0;

        int level = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();            
            for (int i = 0; i < size; i++) {
            //每次都将这一层的所有结点全部入队,然后将其父结点出队
                TreeNode node = queue.remove();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            //每加一层,层数就加一
            level ++;
        }
        return level;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值