简体   繁体   中英

Linked list in Java - comparing two lists

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM