本打算用类似于最长上升子序列的动态规划记忆化搜索实现,意外的竟然直接用回溯搜索就能pass Judge Large了,测试用例并不大是一个原因,还有就是子状态数可能要比想像中的要少。
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
// Start typing your Java solution below
// DO NOT write main() function
if (s3.length() != s1.length() + s2.length())
return false;
else return dp(s1, s1.length()-1, s2, s2.length()-1, s3, s3.length()-1);
}
public boolean dp(String s1, int end1, String s2, int end2, String s3, int end3) {
if (end3 < 0)
return true;
else if (end1 <0) {
return s2.substring(0,end2+1).equals(s3.substring(0, end3+1));
} else if (end2 < 0) {
return s1.substring(0,end1+1).equals(s3.substring(0, end3+1));
}
char c3 = s3.charAt(end3);
char c1 = s1.charAt(end1);
char c2 = s2.charAt(end2);
if (c3 == c1 && c3 == c2) {
return dp(s1, end1-1, s2, end2, s3, end3-1) || dp(s1, end1, s2, end2-1, s3, end3-1);
} else if (c3 == c1)
return dp(s1, end1-1, s2, end2, s3, end3-1);
else if (c3 == c2)
return dp(s1, end1, s2, end2-1, s3, end3-1);
else
return false;
}
}
运行结果:
Run Status:
Accepted!
Program Runtime: 640 milli secs
Program Runtime: 640 milli secs