开发者

Linked list in Java - comparing two lists

I need to create a recursive method in java which checks two Char lists. 开发者_如何学JAVAIf 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?


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)


The in order requirement also simplifies the problem.

Consider that both lists are iterated over at the same time with slightly different advancing rules:

  1. When is the list "to find" advanced to the next node?
  2. When is the list which may contain the "to find" list advanced to the next node?
  3. At what point is it determined that the "to find" list is not contained in the other?
  4. At what point is a match determined?
  5. How can it be done iterating each list? How can it be done recursively?

Happy coding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜