Reputation: 11
I need to create a recursive method in java which checks two Char lists. If the second list includes all the chars in the first list at least once and in the same order it should return true, else it should return false. for example:
List 1: "abbcd"(every char in a node), List 2: "abbcccddd"(every char in node) This should return true.
Example 2: "abbcd", List 2: "abcd" this should return false.
I have some ideas but can't reach a definite solution. Ideas anyone?
Upvotes: 0
Views: 1369
Reputation:
The in order requirement also simplifies the problem.
Consider that both lists are iterated over at the same time with slightly different advancing rules:
Happy coding.
Upvotes: 0
Reputation: 495
I'll assume that you use the usual node structure with a data element and a reference to the next node. Then one can define the function as follows:
contains(null, haystack) = true (since every string contains the empty string)
contains(pattern, null) = false (since the empty string doesn't contain any patterns)
contains(pattern, haystack) = contains(pattern.next, haystack.next) if pattern.data = haystack.data (we found a match and proceed to the next item in both lists)
contains(pattern, haystack) = contains(pattern.next, haystack.next) else (we found no match and try it with the next character in the haystack)
Upvotes: 1