有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中搜索查找不相邻但顺序相同的子集合

在Java(8)中,如果一个集合(列表或集合)是另一个集合的子集,尽管元素不相邻,例如[1,2,3,4,5]作为大集合,如果我想搜索[2,3,4]return true,也要搜索[2,5]return true,但[4,2]return false,尽管4和2在集合中,但顺序不相同,我该如何查找

有没有一个实用工具可以帮我做这件事? 或者一段代码正确地完成了这项工作

谢谢


共 (4) 个答案

  1. # 1 楼答案

    如果a包含b,则此函数返回true

    此函数将集合转换为数组,如果您的集合类未实现.toArray()函数,它将无法工作

    public class CollectionUtils {
        private CollectionUtils() {
        }
    
        /**
         * @return true if A contains B in order
         */
        public static <T> boolean checkAcontainsB(Collection<T> a, Collection<T> b) {
            if (a == null || b == null || b.size()>a.size()) {
                return false;
            }
            if (b.isEmpty()) {
                return true;
            }
            final Object[] aElements = a.toArray();
            final Object[] bElements = b.toArray();
    
            for (int i = 0; i < aElements.length; i++) {
    
                int bIndex = 0;
                for(int j = i; j< aElements.length; j++) {
                    if(aElements[j] == bElements[bIndex]) {
                        bIndex++;
                        if(bIndex>=bElements.length) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    
    }
    

    您可以测试它:

    @Test
    public void test() {
        Assert.assertFalse(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,3,4,5)));
        Assert.assertTrue(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,3,4)));
        Assert.assertTrue(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,4)));
        Assert.assertTrue(CollectionUtils.contains(Arrays.asList(1,2,3,4,1,2,3,4), Arrays.asList(3,4,2)));
        Assert.assertFalse(CollectionUtils.contains(Arrays.asList(1,2,3,4), Arrays.asList(2,3,4,5,6)));
    }
    
  2. # 2 楼答案

    我不知道你的问题有什么通用的解决方案,但在下面你可以找到一个定制的解决方案

    public static boolean containsArray(int[] a, int[] s) {
        if (a == null || s == null) return false;
        if (a.length < s.length) return false;
    
        int i = -1;
        for (int current : s) {
            do {
                i++;
                if (i == a.length) {
                    return false;
                }
            } while (a[i] != current);
        }
    
        return true;
    }
    
  3. # 3 楼答案

    还没有完全测试过,但你可以试试这样的

        int[] x = {1,2,3,4,5};
        int[] y = {2,5};
        int yIndex = 0;
    
        for(int i: x){
            if(y[yIndex] == i){
                yIndex++;
                if(yIndex >= y.length){
                    break;
                }
            }
        }
    
        System.out.println(yIndex == y.length ? "Match" : "Not Match");
    
  4. # 4 楼答案

    您可以很容易地使用集合提供的一种实用方法,该方法完全符合您的意图

        Collections.disjoint(c1, c2)
    

    如果传递的两个集合没有任何公共项,则上述方法返回true,反之亦然。正是你想要的