一、力扣
1、反转偶数长度组的节点
class Solution {
public ListNode reverseEvenLengthGroups(ListNode head) {
int point = 1;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
ListNode tail = dummy;
while (cur != null) {
int ind = 0;
while (ind < point && cur != null) {
tail = cur;
cur = cur.next;
ind++;
}
if (ind % 2 == 1) {
pre = tail;
} else {
ListNode secHead = null;
ListNode start = pre.next;
while (start != cur) {
ListNode nextStart = start.next;
start.next = secHead;
secHead = start;
start = nextStart;
}
pre.next.next = cur;
ListNode temp = pre.next;
pre.next = secHead;
pre = temp;
}
point++;
}
return dummy.next;
}
}
2、跳跃游戏 II
只需要遍历到n-1因为最后一个不需要造桥。
class Solution {
public int jump(int[] nums) {
int nextRight = 0;
int las = 0;
int ans = 0;
int n = nums.length;
for (int i = 0; i < n - 1; i++) {
nextRight = Math.max(nextRight, i + nums[i]);
if (i == las) {
ans++;
las = nextRight;
}
}
return ans;
}
}
3、正则表达式匹配
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
// dp[i][j]表示s的前i个字符与p的前j个字符是否匹配
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true; // 空字符串与空模式匹配
// 初始化:处理模式p中可能的前导'*'(如"a*b*"可匹配空字符串)
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*' && j >= 2) {
// 当前字符是'*'且前面有字符,则继承前两个字符的匹配结果(即忽略该'*'及其前一个字符)
dp[0][j] = dp[0][j - 2];
}
}
// 填充动态规划表
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
char sc = s.charAt(i - 1); // s的第i个字符
char pc = p.charAt(j - 1); // p的第j个字符
// 情况1:当前字符匹配或p中是通配符'.'
if (sc == pc || pc == '.') {
dp[i][j] = dp[i - 1][j - 1];
}
// 情况2:p中是'*',需处理零次或多次匹配
else if (pc == '*') {
// 零次匹配:忽略'*'及其前一个字符,继承dp[i][j-2]
dp[i][j] = dp[i][j - 2];
// 多次匹配:若前一个字符匹配当前字符或为'.',则继承dp[i-1][j]
if (p.charAt(j - 2) == sc || p.charAt(j - 2) == '.') {
dp[i][j] |= dp[i - 1][j]; // 合并零次和多次匹配的结果
}
}
// 其他不匹配情况,dp[i][j]保持为false
}
}
// 返回整个字符串s与模式p的匹配结果
return dp[m][n];
}
}