【动态规划+滚动数组】Interleaving String
2015-04-10 18:05
288 查看
题目:leetcode
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 =
s2 =
When s3 =
When s3 =
分析:
1、检查长度,长度不符合 “s3.size()==s1.size()+s2.size()” 的返回false;
2、利用滚动数组,使本来需要m*n额外辅助空间减少到n。为了方便,额外使用数组same_s1和same_s2,分别记录数组s1、s2的前n位是否和s3相等。
时间复杂度O(n^2),空间复杂度O(n);
Interleaving String
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.
分析:
1、检查长度,长度不符合 “s3.size()==s1.size()+s2.size()” 的返回false;
2、利用滚动数组,使本来需要m*n额外辅助空间减少到n。为了方便,额外使用数组same_s1和same_s2,分别记录数组s1、s2的前n位是否和s3相等。
时间复杂度O(n^2),空间复杂度O(n);
bool isInterleave(string s1, string s2, string s3) { if(s1.size()>s2.size()) return isInterleave(s2,s1,s3); if(s3.size()!=s1.size()+s2.size()) return false; if(s1.empty()) return s2==s3; if(s2.empty()) return s1==s3; const int n2=s2.size(); const int n1=s1.size(); bool f[n2]; bool same_s1[n1],same_s2[n2]; same_s1[0]=s3[0]==s1[0]; for(int i=1;i<s1.size();i++) { if(s1[i]==s3[i] && same_s1[i-1]) same_s1[i]=true; else same_s1[i]=false; } same_s2[0]=s3[0]==s2[0]; for(int i=1;i<s2.size();i++) { if(s2[i]==s3[i] && same_s2[i-1]) same_s2[i]=true; else same_s2[i]=false; } if( (s1[0]==s3[0]&&s2[0]==s3[1]) || (s1[0]==s3[1]&&s2[0]==s3[0])) f[0]=true; else f[0]=false; //s1出下标为0的位,s2出下标为[0,j]的位 for(int j=1;j<n2;j++) { f[j]= s3[j+1]==s2[j] && f[j-1];//s1[0]不在匹配的最后 if(s3[j+1]==s1[0] && !f[j] && same_s2[j])//s1[0]在匹配的最后 { f[j]=true; } } //s1出[0,i]的位,s2出[0,j]的位 for(int i=1;i<s1.size();i++) { for(int j=0;j<s2.size();j++) { if(j==0) { f[j]=s3[i+j+1]==s1[i]&&f[j]; if(!f[j]) { f[j]= s3[i+j+1]==s2[j] && same_s1[i]; } } else { f[j]= (s3[i+j+1]==s1[i]&&f[j]) || (s3[i+j+1]==s2[j] && f[j-1]); } } } return f[n2-1]; }
相关文章推荐
- leetcode:Interleaving String 使用动态规划求解的java源代码
- LeetCode(97) Interleaving String(动态规划)
- 二维动态规划——Interleaving String
- Interleaving String,交叉字符串,动态规划
- [算法作业-动态规划][LeetCode] 97. Interleaving String
- Interleaving String (字符串组合,动态规划) 【leetcoode】
- leetcode_[python/C++]_97_Interleaving String_动态规划
- 13.6—动态规划—Interleaving String
- LeetCode Interleaving String(动态规划)
- LeetCode 笔记系列 20 Interleaving String [动态规划的抽象]
- [LeetCode]Interleaving String关于遍历和动态规划
- 【leetcode】97. Interleaving String【java】动态规划,并有详细解释
- [LeetCode] Interleaving String
- LeetCode: Interleaving String
- Interleaving string
- Interleaving String
- [LeetCode]Interleaving String
- 1119. Metro(动态规划,滚动数组)
- [Leetcode]Interleaving String
- leetcode - Interleaving String