题目一:Interleaving String
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:3
www.wtgvsc.com
s1 = "aabcc"
,
s2 = "dbbca"
,
When s3 = "aadbbcbcac"
, return true.
When s3 = "aadbbbaccc"
, return false.
这道题是一道明显的DP题目,由于在这之前DP类型做得比较少,所以这道题目可能分析得不是那么好,网友们见谅哈!
居然题目是一个DP动态规划的题目,那么必定有一个状态转移方程式。
如果我们用一个boolean flags[][] 二维数组来存储状态信息
flags[i][j] 表示取S1中的前i个数和取S2中的前j个数
flags[i][j] == true : 表示S3的前(i+j)长度的子串还是满足S1和S2交叉结合的
flags[i][j] == false: 表示不满足
首先我们来讲下直到S3前面(i+j)长度的子串还满足可以由S1和S2交叉构成的
条件是(flags[i][j-1] == true && S2[j-1] == S3[i+j-1] ) || (flags[i-1][j] == true && S1[i-1] == S3[i+j-1] )
最后我们所要的结果就是当S1取S1.length长度,而S2取S2.length长度时,看是否满足,即flags[S1.length][S2.length]是否为true
AC代码:
- public class Solution {
- public boolean isInterleave(String s1, String s2, String s3) {
- int len1 = s1.length();
- int len2 = s2.length();
- int len3 = s3.length();
- //长度不等直接干掉
- if (len3 != (len2+len1)){
- return false;
- }
- //状态存储的二维数组
- boolean flags[][] = new boolean[len1+1][len2+1];
- flags[0][0] = true;
- for (int i=1; i<=len1; ++i){
- flags[i][0] = flags[i-1][0] && (s1.charAt(i-1) == s3.charAt(i-1));
- }
- for (int j=1; j<=len2; ++j){
- flags[0][j] = flags[0][j-1] && (s2.charAt(j-1) == s3.charAt(j-1));
- }
- for (int i=1; i<=len1; ++i){
- for (int j=1; j<=len2; ++j){
- flags[i][j] = ((flags[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1))
- || (flags[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1)));
- }
- }
- return flags[len1][len2];
- }
- }
题目二:Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
分析:
题目要求我们判断一下一棵树,是否满足搜索二叉树的性质:
1、树的左边的所有结点都不能大于根的值
2、树的右边的所有结点都不能小于根的值