(lintcode)第29題交叉字串
阿新 • • 發佈:2018-12-24
比如 s1 = "aabcc" s2 = "dbbca"
- 當 s3 = "aadbbcbcac",返回 true.
- 當 s3 = "aadbbbaccc", 返回 false.
思路:這道題一開始我是使用三個下標分別對應3個字串,如果匹配上,那麼就會往後移一位,但是這樣就會有一個嚴重錯誤就是當s1=aabc,s2=aade,s3=aaddaabce,如果匹配上一位就後移,那麼假設首先對s1匹配,那麼直到aab的時候就會發現b這一位是沒有辦法匹配的,這時候和s2也沒有辦法匹配上,就會返回無法匹配,出現這個現象的原因是我寫的程式碼沒有考慮到回溯。
另一種思路是看別人的程式碼才想明白的,就是動態規劃(DP),把一個大問題簡化成為一個簡單的問題,我們考慮長度為l1的s1,和長度為l2的s2能不能匹配成為長度為l1+l2的s3。
程式碼如下:
public class Solution { /** * Determine whether s3 is formed by interleaving of s1 and s2. * @param s1, s2, s3: As description. * @return: true or false. */ public boolean isInterleave(String s1, String s2, String s3) { if(null == s1 || null == s2 || null == s3 || s1.length() + s2.length() != s3.length()) return false; if(s1.length() <= 0 && s2.length() <= 0 && s3.length() <= 0) return true; boolean[][] common = new boolean[s1.length() + 1][s2.length() + 1]; for(int i = 1;i <= s1.length();i++) { if(s1.charAt(i - 1) == s3.charAt(i - 1)) { common[i][0] = true; } } for(int i = 1;i <= s2.length();i++) { if(s2.charAt(i - 1) == s3.charAt(i - 1)) { common[0][i] = true; } } for(int i = 1;i <= s1.length();i++) { for(int j = 1;j <= s2.length();j++) { if(s1.charAt(i - 1) == s3.charAt(i + j - 1)) { common[i][j] = common[i - 1][j]; } if(common[i][j]) { continue; } if(s2.charAt(j - 1) == s3.charAt(i + j - 1)) { common[i][j] = common[i][j - 1]; } } } return common[s1.length()][s2.length()]; } }