Interleaving String的两种面试题:
1. 给定两个String, 求出所有interleaving string的可能
2. 给定两个String,判断第三个String是不是他们的interleaving string
第一感觉必然是递归,但是two pointer和permutation的思路还是一闪而过。 Two Pointer是对的,但是permutation会打破string的顺序,所以不予考虑。
比较难于理解的点是这个递归运用了pointer的移动,尤其是第一个问题更加明显。下面是代码:
1. 求出所有可能的interleaving string
class Test{
public static void main(String[] args){
ArrayList<String> res = new ArrayList<String>();
String str1 = "AB";
String str2 = "CD";
int len1 = str1.length(), len2 = str2.length(), len = len1 + len2;
char[] chs = new char[len];
recImp(res, chs, 0, str1, str2, 0, 0);
for(int i=0; i<res.size(); i++)
System.out.println(res.get(i));
}
public static void recImp(ArrayList<String> res, char[] chs, int pos, String str1, String str2, int p1, int p2){
if(pos == chs.length){
res.add(new String(chs));
return;
}
if(p1 < str1.length()){
chs[pos] = str1.charAt(p1);
recImp(res, chs, pos+1, str1, str2, p1+1, p2);
}
if(p2 < str2.length()){
chs[pos] = str2.charAt(p2);
recImp(res, chs, pos+1, str1, str2, p1, p2+1);
}
}
}
2. leetcode原题,求s3是不是s1和s2的interleaving string
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if (s1.length() + s2.length() != s3.length()) return false;
return dfs(s1,0,s2,0,s3,0);
}
public boolean dfs(String s1, int pos1, String s2, int pos2, String s3, int pos3){
if (pos3==s3.length()) return true;
if (pos1==s1.length()) return s2.substring(pos2).equals(s3.substring(pos3));
if (pos2==s2.length()) return s1.substring(pos1).equals(s3.substring(pos3));
char c1 = s1.charAt(pos1);
char c2 = s2.charAt(pos2);
char c3 = s3.charAt(pos3);
if(c1==c3 && c2==c3)
return dfs(s1,pos1+1,s2,pos2,s3,pos3+1) || dfs(s1,pos1,s2,pos2+1,s3,pos3+1);
else if (c1==c3)
return dfs(s1,pos1+1,s2,pos2,s3,pos3+1);
else if (c2==c3)
return dfs(s1,pos1,s2,pos2+1,s3,pos3+1);
else
return false;
}
}
小结:
对于理解递归非常有帮助的一道题。