97/100 Interleaving String/Same Tree
来源:互联网 发布:吃鸡网络延迟 编辑:程序博客网 时间:2024/05/20 05:29
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = “aabcc”,
s2 = “dbbca”,
When s3 = “aadbbcbcac”, return true.
When s3 = “aadbbbaccc”, return false.
可以用递归做,每匹配s1或者s2中任意一个就递归下去。但是会超时。
因此考虑用动态规划做。
s1, s2只有两个字符串,因此可以展平为一个二维地图,判断是否能从左上角走到右下角。
当s1到达第i个元素,s2到达第j个元素:
地图上往右一步就是s2[j-1]匹配s3[i+j-1]。
地图上往下一步就是s1[i-1]匹配s3[i+j-1]。
示例:s1=”aa”,s2=”ab”,s3=”aaba”。标1的为可行。最终返回右下角。
0 a b0 1 1 0a 1 1 1a 1 0 1
class Solution {public: bool isInterleave(string s1, string s2, string s3) { int m = s1.size(); int n = s2.size(); if(m+n != s3.size()) return false; vector<vector<bool> > path(m+1, vector<bool>(n+1, false)); for(int i = 0; i < m+1; i ++) { for(int j = 0; j < n+1; j ++) { if(i == 0 && j == 0) // start path[i][j] = true; else if(i == 0) path[i][j] = path[i][j-1] & (s2[j-1]==s3[j-1]); else if(j == 0) path[i][j] = path[i-1][j] & (s1[i-1]==s3[i-1]); else path[i][j] = (path[i][j-1] & (s2[j-1]==s3[i+j-1])) || (path[i-1][j] & (s1[i-1]==s3[i+j-1])); } } return path[m][n]; }};
笔记:字符串处理,直观可以想到用递归做的题,基本都可以用DP求解.100 Same Tree:Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3]Output: true
Example 2:
Input: 1 1 / \ 2 2 [1,2], [1,null,2]Output: false
Example 3:
Input: 1 1 / \ / \ 2 1 1 2 [1,2,1], [1,1,2]Output: false
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p == NULL && q == NULL) return true; else if(p == NULL && q != NULL) return false; else if(p != NULL && q == NULL) return false; else if(p->val != q->val) return false; else return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); }};
笔记:简单的递归调用,思路要清晰。
阅读全文
0 0
- 97/100 Interleaving String/Same Tree
- LeetCode 97 Interleaving String
- LeetCode(97) Interleaving String
- [leetcode 97] Interleaving String
- [leetcode] 97 Interleaving String
- 【LeetCode】【97】Interleaving String
- leetcode || 97、Interleaving String
- [leetcode 97]Interleaving String
- leetcode 97: Interleaving String
- leetCode 97:Interleaving String
- 97Interleaving String
- 97 - Interleaving String
- Leetcode-97 Interleaving String
- 97Interleaving String
- Leetcode 97 Interleaving String
- LeetCode 97 Interleaving String
- Leetcode 97, Interleaving String
- Leetcode Interleaving String 97
- 解决webapps目录下不存在Tomcat的部署项目
- C++ Task 的实现(lambda 是个好东西)
- Cordova插件实现原理概论
- Python3与OpenCV3.3 图像处理(一)--环境搭建与简单DEMO
- python中 %总结
- 97/100 Interleaving String/Same Tree
- CF#420 B. Okabe and Banana Trees 思维|暴力|几何
- 使用SwingWorker类完成耗时操作
- Python练习实例3
- Python学习教程(八)——异常
- 字符串的大小及与指针的关系
- ssh-keygen的-C后面的邮箱有什么用?
- 个人总结33
- 汇编与C/C++内联嵌入汇编