java 查找包含给定子序列的最短间隔的Java实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 查找包含给定子序列的最短间隔的Java实现相关的知识,希望对你有一定的参考价值。

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class ShortestSubsequenceInterval {

  public static void main(String[] args) {
    String[] words = {"*", "*", "*", "-", "*", "*", "*", "-", "*", "*", "*", "*"};
    String[] keys = {"*", "*", "*", "*"};
    int[] result = shortestSubsequenceInterval(words, keys);
    for (int i: result) {
      System.out.println(i);
    }
  }

  public static int[] shortestSubsequenceInterval(String[] wordSequence, String[] keySequence) {
    if (wordSequence == null || keySequence == null) {
      return null;
    }

    Map<String, Set<Integer>> keyToIndices = new TreeMap<>();
    for (int i = 0; i < keySequence.length; i++) {
      String key = keySequence[i];
      if (!keyToIndices.containsKey(key)) {
        Set<Integer> indicesSet = new TreeSet<>();
        indicesSet.add(i);
        keyToIndices.put(key, indicesSet);
      }
      else {
        keyToIndices.get(key).add(i);
      }
    }

    int[] result = null;
    int minIntervalLength = Integer.MAX_VALUE;
    Map<Integer, Integer> prefixLengthToStartIndex = new TreeMap<>();
    Map<Integer, Integer> prefixLengthToStartIndexWriteUpdates = new TreeMap<>(); // write to this map then update together, in order to avoid one update affecting others (which leads to wrong result)
    for (int i = 0; i < wordSequence.length; i++) {
      String word = wordSequence[i];
      Set<Integer> keyIndices = keyToIndices.get(word);
      if (keyIndices == null) continue;

      prefixLengthToStartIndexWriteUpdates.clear();
      for (int keyIndex: keyIndices) {
        int prefixLength = keyIndex;
        Integer prefixStartIndex = (keyIndex == 0)? new Integer(i): prefixLengthToStartIndex.get(prefixLength);
        if (prefixStartIndex == null) continue;

        prefixLengthToStartIndexWriteUpdates.put(prefixLength + 1, prefixStartIndex);
        if (prefixLength + 1 == keySequence.length) {
          int intervalLength = i - prefixStartIndex + 1;
          if (intervalLength < minIntervalLength) {
            minIntervalLength = intervalLength;
            result = (result == null)? new int[2]: result;
            result[0] = prefixStartIndex;
            result[1] = i;
          }
        }
      }
      prefixLengthToStartIndex.putAll(prefixLengthToStartIndexWriteUpdates);
    }

    return result;
  }

}

以上是关于java 查找包含给定子序列的最短间隔的Java实现的主要内容,如果未能解决你的问题,请参考以下文章

从一道算法面试题看我国信息科技的原创性不足:查找包含所有元素的最短子数组

在java中初始化字符串列表的最短方法是啥?

查找另一个日期之前的最短日期

二分查找的妙用:判定子序列

做wget的最短Java程序

java 大于等于ķ的最短子数组长度