一开始用递归。大数据超时了。后来网上看了一下,是动态规划。归根结底就是有重复子问题,比如bbbbaaaa由bbaa和bbaa来匹配的话,那么无论第一个b选s1还是s2的,都会出现baa和baa这样的子问题。
那么由于s1+s2==s3,只需要用二维数组记录状态就行了。状态转移方程可详见:http://blog.unieagle.net/2012/09/29/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Ainterleaving-string%EF%BC%8C%E4%BA%8C%E7%BB%B4%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/
这是最后过得动态规划版本:(我看有的人把数组起名为matrix)
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { // Start typing your Java solution below // DO NOT write main() function if (s1.length() + s2.length() != s3.length()) return false; boolean[][] status = new boolean[s1.length()+1][s2.length()+1]; int len1 = s1.length(); int len2 = s2.length(); int len3 = s3.length(); status[0][0] = true; for (int i = 1; i < s1.length()+1; i++) { status[i][0] = status[i-1][0] && s1.charAt(len1 - i) == s3.charAt(len3 - i); } for (int j = 1; j < s2.length()+1; j++) { status[0][j] = status[0][j-1] && s2.charAt(len2 - j) == s3.charAt(len3 - j); } for (int i = 1; i < s1.length()+1; i++) { for (int j = 1; j < s2.length()+1; j++) { status[i][j] = s3.charAt(len3 - i - j) == s1.charAt(len1 - i) && status[i-1][j] || s3.charAt(len3 - i - j) == s2.charAt(len2 - j) && status[i][j-1]; } } return status[len1][len2]; } }
这是大数据超时的版本,我想如果用动态规划那个数组记录一下计算过的状态也是能过得。
public class Solution { public boolean isInterleave(String s1, String s2, String s3) { // Start typing your Java solution below // DO NOT write main() function if (s1.length() + s2.length() != s3.length()) return false; return isInterleave(s1, s2, s3, 0, 0, 0); } public boolean isInterleave(String s1, String s2, String s3, int idx1, int idx2, int idx3) { if (idx3 == s3.length()) { if (idx1 == s1.length() && idx2 == s2.length()) return true; else return false; } boolean cond1 = idx1 < s1.length() && s1.charAt(idx1) == s3.charAt(idx3); boolean cond2 = idx2 < s2.length() && s2.charAt(idx2) == s3.charAt(idx3); if (cond1 && cond2) { return isInterleave(s1, s2, s3, idx1+1, idx2, idx3+1) || isInterleave(s1, s2, s3, idx1, idx2+1, idx3+1); } else if (cond1) { return isInterleave(s1, s2, s3, idx1+1, idx2, idx3+1); } else if (cond2) { return isInterleave(s1, s2, s3, idx1, idx2+1, idx3+1); } return false; } }