I'm trying to check if a list is a subset of another in java . I used the for loop to check the elements and i have a variable called same that is incremented each time the elements are the same . The problem is that the list returns true only if the elements are in identical positions
For example :
(0,1) (0,1,2,3 ) true
(1,0) (0,1,2,3) false
I have written the code below :
public Boolean contains(ItemsList ilist) {
int same = 0;
if (empty()) {
return false;
} else {
ItemNode a = this.first;
ItemNode b = ilist.first;
for (b = ilist.first; b != null; b = b.next) {
for (a = this.first; a != null; a = a.next) {
if (a.item == b.item) {
same++;
}
}
}
}
return (same > 0);
}
解决方案
The approach to solve this problem is very similar to solving substring matching problem.
You start by checking if the first element of the supposedly subset list(henceforth to be refereed to as SSL).
Once you get a match, note the index (henceforth will be referred to as myGuy in the main list where the match is found, proceed to check if the subsequent elements of SSL matches the main list.
If your match is complete then simply return. If not, then you can do one of the two. If the main list has elements left, then increment myGuy and then it becomes the new index from where you start to iterate in the main list.
If no elements are left and still no complete match then it's not a subset.
Here is how you can do it in Java:
private static boolean checkSubList(int[] mainList, int[] subList) {
int currentIteratingPointer;
int matchCounter = 0;
for (int i = 0; i < mainList.length; i++) {
currentIteratingPointer = i;
for (int j = 0; j < subList.length; j++) {
if (mainList[currentIteratingPointer] == subList[j]) {
System.out.println(mainList[currentIteratingPointer]);
++matchCounter;
++currentIteratingPointer;
} else {
--matchCounter;
break;
}
}
i = currentIteratingPointer;
}
return matchCounter == subList.length; // You can count the number of occurance of the sublist if you change
// it to int and return the matchCounter a
}