代码改变世界

Check whether string is interleaved

2010-10-01 09:59  wansishuang  阅读(151)  评论(0编辑  收藏  举报

Three strings say A,B,C are given to you. Check whether 3rd string is interleaved from string A and B.
Ex: A="abcd" B="xyz" C="axybczd". answer is yes.

 

如果元素不相同的话,可以类似归并排序在0(N)时间内解决。

如果不想同的话,可以递归的解决

f(a, b, c)

{

if(c.size = 0 && a.size==0 &&b.size == 0) return 1;

else if(c.size == 0) return 0;

int ans = 0;

if(a[0] = c[0]) ans += f(a+1, b, c+1);

if(b[0] = c[0]) ans += f(a, b+1, c+1);

return ans > 0 ? 1: 0;

}

可以考虑加上个备忘录,减少重复递归