14. 最长公共前缀【简单】
https://leetcode-cn.com/problems/longest-common-prefix/
采用纵向扫描算法
class Solution {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
int n = strs.length, m = strs[0].length();
for (int i = 0; i < m; i++) { // i 控制字符串的位数
char c = strs[0].charAt(i);
for (int j = 1; j < n; j++) { // j 控制遍历每个字符串
if (strs[j].length() == i || strs[j].charAt(i) != c)
return strs[0].substring(0, i);
}
}
return strs[0];
}
}
206.反转链表【简单】
https://leetcode-cn.com/problems/reverse-linked-list/
虚拟头节点,链表题多画图
public ListNode reverseList(ListNode head) {
ListNode dummy = null;
ListNode pre = dummy, cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
21.合并两个有序联表【简单】
https://leetcode-cn.com/problems/merge-two-sorted-lists/
虚拟头节点(方便输出结果的head)、双指针
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(-1);
ListNode p = dummy, p1 = list1, p2 = list2;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
p.next = p1;
p1 = p1.next;
}
else if (p2.val <= p1.val) {
p.next = p2;
p2 = p2.next;
}
p = p.next;
}
if (p1 != null) {
p.next = p1;
}
else if (p2 != null) {
p.next = p2;
}
return dummy.next;
}
718. 最长重复子数组【中等】
https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/
采用动态规划。
有点类似昨天写的最长子序列,最长子数组也可以理解为连续子序列。
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int n = nums1.length, m = nums2.length;
int[][] dp = new int[n+1][m+1];
int result = 0;
for(int i = 1; i < n+1; i++) {
for (int j = 1; j < m+1; j++) {
if (nums1[i-1] == nums2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
result = Math.max(result, dp[i][j]);
}
}
}
return result;
}
}
300. 最长递增子序列【中等】
https://leetcode-cn.com/problems/longest-increasing-subsequence/
采用动态规划。
dp[ i ] 表示 nums[ i ] 结尾的最长递增子序列的长度。
class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
int res = 0;
Arrays.fill(dp, 1); // 初始化dp数组为1,即递增序列最小值为1。
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j]+1); // 计算出的 dp[j] + dp[j]+1 的最大值
}
}
}
for (int i = 0; i < dp.length; i++) {
res = Math.max(res, dp[i]);
}
return res;
}
}