Reputation: 53
I am trying this problem:
Suppose you are given three strings of characters: X, Y, and Z, where |X| = n, |Y| = m, and |Z| = n+m.Z is said to be a shuffle of X and Y if and only if Z can be formed by interleaving the characters from X and Y in a way that maintains the left-to right ordering of the characters from each string.
Give an efficient algorithm that determines whether Z is a shuffle of X and Y.
Hint: the values of the dynamic programming matrix you construct should be Boolean, not numeric
What I don't understand is why everyone is presenting a dynamic programming recursive solution.
Can't we just do the following n+m algo:
Maintain two pointers i and j, i points to chars in string x and j for string y.
Iterate (with iterator k) through z, for every char z[k] if it match x[i] increment i, if it match y[j] increment j
2.1. if k > i+j then return false
2.2. if k == z.length() and i or j != x.length(), y.length() respectively then return false
return true
edited according to Tanmay Patil 's post
Upvotes: 2
Views: 855
Reputation: 7057
Well, the problem statement clearly says
Give an efficient dynamic programming algorithm
So that should explain
everyone is presenting a dynamic programming recursive solution
Even then, it can be solved in an iterative way as you mentioned. And it is not a n^2 algorithm, it's time complexity is n+m
Good luck.
Upvotes: 3
Reputation:
You're right.
You never, ever HAVE TO use recursive algorithms. You're free to do so, but you can ALWAYS use an interative routine.
In this example, you could use arrays or allocate a memory block large enough to hold the result.
Upvotes: 0