logo CodeStepByStep logo

canInterleave

Language/Type: Java recursion backtracking strings
Related Links:

Write a recursive method named canInterleave that accepts three strings s1, s2, and s3 as parameters and uses backtracking to determine whether s3 can be formed by interleaving the characters of s1 and s2 in some combination, returning true if so and false if not. For example, the call of canInterleave("aabcc", "dbbca", "aadbbcbcac") should return true because you can form "aadbbcbcac" by taking the two 'a' characters from s1, then the 'd' from s2, and so on, to make the given result. The given s3 must use all characters from both s1 and s2 in the same relative order.

The call of canInterleave("abc", "dde", "addce") would return false because the 'b' from s1 is not used in s3. The call of canInterleave("abc", "dde", "adbdeca") would return false because s3 contains an extra 'a' character. The call of canInterleave("abc", "dde", "cdbdea") would return false because the 'c', 'b', and 'a' from s1 occur in the wrong relative order.

Constraints: Do not declare any global variables. Your algorithm must be recursive and must use backtracking; you should not need to use any loops. You are allowed to define other "helper" methods if you like; they are subject to these same constraints.

Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.