java 判断 子集,如何检查列表是否是Java中另一个列表的子集?

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值