题目主要来源:LeetCode。主要选自剑指offer、程序员面试宝典。
每日尽可能保持 N+1 道题,N 取 0 到 9。部分解法是从LeetCode上大佬们的解法中拿过来的,如有侵权,告知立删
文章目录
0x01 剑指 Offer 19. 正则表达式匹配
/**
* JZ19 困难题,躺平了,直接抄答案
*
* @author Anjude
* @date 2021/7/13 21:40
*/
public class JZ19 {
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] f = new boolean[m + 1][n + 1];
f[0][0] = true;
for (int i = 0; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (p.charAt(j - 1) == '*') {
f[i][j] = f[i][j - 2];
if (matches(s, p, i, j - 1)) {
f[i][j] = f[i][j] || f[i - 1][j];
}
} else {
if (matches(s, p, i, j)) {
f[i][j] = f[i - 1][j - 1];
}
}
}
}
return f[m][n];
}
public boolean matches(String s, String p, int i, int j) {
if (i == 0) {
return false;
}
if (p.charAt(j - 1) == '.') {
return true;
}
return s.charAt(i - 1) == p.charAt(j - 1);
}
}
0x02 剑指 Offer 24. 反转链表
/**
* JZ24 可用递归和迭代
*
* @author Anjude
* @date 2021/7/13 22:07
*/
public class JZ24 {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
// ListNode pre = null;
// ListNode cur = head;
// while (cur != null) {
// ListNode next = cur.next;
// cur.next = pre;
// pre = cur;
// cur = next;
// }
// return pre;
}
}
0x03 剑指 Offer 18. 删除链表的节点
/**
* JZ18 双指针
*
* @author Anjude
* @date 2021/7/14 0:43
*/
public class JZ18 {
public ListNode deleteNode(ListNode head, int val) {
if (head == null) return head;
if (head.val == val) return head.next;
ListNode pre = head;
ListNode cur = head.next;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
break;
}
pre = pre.next;
cur = cur.next;
}
return head;
}
}