NC92 最长公共子序列-II
1、解题思路
使用dp的思想求出最长长度,然后根据长度反推出字符串。
2、代码
import java.util.*;
public class Solution {
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
public String LCS (String s1, String s2) {
// write code here
// write code here
int r = s1.length();
int c = s2.length();
int[][] dp = new int[r + 1][c + 1];
for (int i = 0; i <= c; i++) {
dp[0][i] = 0;
}
for (int i = 0; i <= r; i++) {
dp[i][0] = 0;
}
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
char c1 = s1.charAt(i-1);
char c2 = s2.charAt(j-1);
if (c1 == c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1];
}
}
}
if (dp[r][c] == 0) {
return "-1";
}
char[] arr = new char[dp[r][c]];
int index = arr.length - 1;
while (index >= 0) {
if (s1.charAt(r-1) == s2.charAt(c-1)) {
arr[index--] = s1.charAt(r-1);
r--;
c--;
} else if (dp[r][c] == dp[r - 1][c]) {
r--;
} else {
c--;
}
}
return new String(arr);
}
}
NC36 在两个长度相等的排序数组中找到上中位数
1、解题思路
双指针跑一遍就好了。
2、代码
import java.util.*;
public class Solution {
/**
* find median in two sorted array
* @param arr1 int整型一维数组 the array1
* @param arr2 int整型一维数组 the array2
* @return int整型
*/
public int findMedianinTwoSortedAray (int[] arr1, int[] arr2) {
// write code here
int l1 = 0;
int l2 = 0;
int index = (arr1.length + arr2.length) / 2 - 1;
for (int i = 0; i < index; i++) {
if (arr1[l1] <= arr2[l2]) {
l1++;
} else {
l2++;
}
}
return arr1[l1] < arr2[l2] ? arr1[l1] : arr2[l2];
}
}
NC60 判断一棵二叉树是否为搜索树和完全二叉树
1、解题思路
搜索树:可以先序判断数组是否有序
完全二叉树:层次遍历,出现空节点后面不能再出现节点。
2、代码
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类 the root
* @return bool布尔型一维数组
*/
private void preOrder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
preOrder(root.left, list);
list.add(root.val);
preOrder(root.right, list);
}
private boolean judge1(TreeNode root) {
if (root == null) {
return true;
}
List<Integer> list = new ArrayList<>();
preOrder(root, list);
for (int i = 1; i < list.size(); i++) {
if (list.get(i) < list.get(i - 1)) {
return false;
}
}
return true;
}
private boolean judge2(TreeNode node) {
if (node == null) {
return true;
}
boolean f = false;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
if (temp.left != null) {
if (f) {
return false;
}
queue.add(temp.left);
} else {
f = true;
}
if (temp.right != null) {
if (f) {
return false;
}
queue.add(temp.right);
} else {
f = true;
}
}
}
return true;
}
public boolean[] judgeIt(TreeNode root) {
// write code here
boolean[] judge = new boolean[2];
judge[0] = judge1(root);
judge[1] = judge2(root);
return judge;
}
}