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;
}
}