Leetcode Interleaving String
来源:互联网 发布:浙江外商直接投资数据 编辑:程序博客网 时间:2024/05/16 17:20
题目和算法描述见http://yufeizhaome.wordpress.com/2014/08/19/leetcode-interleaving-string/
递归的算法在两个string相同元素很多的情况下会超时,因为每种可能性都需要走到“底”才能判断,很多“枝”都被重复判断了很多次。
这里采用动态规划的做法,上述链接中的代码已经非常清晰,不再赘述。
#include <iostream>#include <vector>using namespace std;class Solution {public:bool isInterleave(string s1, string s2, string s3) {int l1 = s1.size();int l2 = s2.size();int l3 = s3.size();if (l1 + l2 != l3){return false;}std::vector<std::vector<bool> > canInterleave(l1 + 1, std::vector<bool>(l2 + 1, false));canInterleave[0][0] = true;for (int i = 1; i <= l1; ++i){canInterleave[i][0] = canInterleave[i - 1][0] && s1[i - 1] == s3[i - 1];}for (int i = 1; i <= l2; ++i){canInterleave[0][i] = canInterleave[0][i - 1] && s2[i - 1] == s3[i - 1];}for (int i = 1; i <= l1; ++i){for (int j = 1; j <= l2; ++j){canInterleave[i][j] = (canInterleave[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (canInterleave[i][j - 1] && s2[j - 1] == s3[i + j - 1]);}}return canInterleave[l1][l2];}};int main(){Solution s;string s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac", s4 = "aadbbbaccc";cout<<s.isInterleave(s1, s2, s3)<<endl; // 1cout<<s.isInterleave(s1, s2, s4)<<endl; // 0return 0;}
0 0
- LeetCode: Interleaving String
- LeetCode Interleaving String
- LeetCode: Interleaving String
- [Leetcode] Interleaving String
- [LeetCode] Interleaving String
- leetcode 68: Interleaving String
- [Leetcode] Interleaving String
- LeetCode - Interleaving String
- [LeetCode]Interleaving String
- LeetCode: Interleaving String
- Leetcode: Interleaving String
- [Leetcode]Interleaving String
- Leetcode: Interleaving String
- LeetCode:Interleaving String
- LeetCode-Interleaving String
- [leetcode] Interleaving String@DP
- LeetCode:Interleaving String
- LeetCode - Interleaving String
- 教你使用Navicat Lite新建mysql用户、数据库 by DedeCMS8
- C学习笔记2-int类型数据在内存中的存储形式
- I'm coming!
- 2.2.3 Partition List
- 算法面试题
- Leetcode Interleaving String
- X窗口系统的协议和架构
- 呼呼呼呼呵呵呵呵呵
- 你你你你你您 我我我我我
- 2.2.4 Remove Duplicates from Sorted List
- 使用WM_MOUSEWHEEL
- hdu1525 Euclid's Game , 基础博弈
- MFC Static控件派生类,实现对函数图像的绘制。
- OpenCV3.0来啦