Interleaving String

Given s1s2s3, 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的首字母是否和s3的首字母相同,如果相同则分别进行计算。如果都不相同,返回false。

为了加快速度,使用带标记的递归,也可以用动规实现。

 1 int r[100][100];
 2 void initialize(){
 3     int i,j;
 4     for(i = 0; i < 100; i++){
 5         for(j = 0; j < 100; j++)
 6             r[i][j] = -1;
 7     }
 8     r[0][0] = 1;
 9 }   
10 bool isInterleave2(string s1, string s2, string s3) {
11         // Note: The Solution object is instantiated only once and is reused by each test case. 
12         int l1 = s1.length(), l2 = s2.length(), l3 = s3.length();
13         if(l1 + l2 != l3)
14             return false;
15         if(r[l1][l2] != -1)
16             return r[l1][l2]==1?true:false;
17         bool result = false;
18         if(l1 > 0 && s1[0] == s3[0])
19             result = result||isInterleave2(s1.substr(1), s2, s3.substr(1));
20         if(l2 > 0 && s2[0] == s3[0])
21             result = result||isInterleave2(s1, s2.substr(1), s3.substr(1));
22         if(result)
23             r[l1][l2] = 1;
24         else
25             r[l1][l2] = 0;
26         return result;
27     }
28     bool isInterleave(string s1, string s2, string s3) {
29         initialize();
30         return isInterleave2(s1,s2,s3);
31     }

 第二遍

 

bool isInterleave(string s1, string s2, string s3, int i1, int i2, int l1, int l2, vector<vector<int> > &result){
          if(result[i1][i2] != -1)
              return result[i1][i2] == 1;
          bool tmp = false;
          if(i1 < l1 && s1[i1] == s3[i1+i2])
              tmp = tmp || isInterleave(s1, s2, s3, i1+1, i2, l1, l2, result);
          if(i2 < l2 && s2[i2] == s3[i1+i2])
              tmp = tmp || isInterleave(s1, s2, s3, i1, i2+1, l1, l2, result);
          result[i1][i2] = tmp;
         return tmp;
     }
     bool isInterleave(string s1, string s2, string s3) {
         int l1 = s1.length(), l2 = s2.length(), l3 = s3.length();
         if(l1 + l2 != l3)
             return false;
         vector<vector<int> > result(l1+1, vector<int>(l2+1, -1));
         result[l1][l2] = 1;
         return isInterleave(s1, s2, s3, 0, 0, l1, l2, result);
     }

 

posted on 2013-10-18 20:06  waruzhi  阅读(205)  评论(0编辑  收藏  举报

导航