Google search results: How to find the minimum window that contains all the search keywords?

后端 未结 5 1890
抹茶落季
抹茶落季 2020-12-12 21:10

What is the complexity of the algorithm is that is used to find the smallest snippet that contains all the search key words?

5条回答
  •  囚心锁ツ
    2020-12-12 21:45

    For all the words, maintain min and max index in case there is going to be more than one entry; if not both min and mix index will same.

    import edu.princeton.cs.algs4.ST;
    
    public class DicMN {
    
        ST st = new ST<>();
    
        public class Words {
            int min;
            int max;
            public Words(int index) {
                min = index;
                max = index;
            }
        }
    
        public int findMinInterval(String[] sw) {
    
            int begin = Integer.MAX_VALUE;
            int end = Integer.MIN_VALUE;
            for (int i = 0; i < sw.length; i++) {
                if (st.contains(sw[i])) {
                    Words w = st.get(sw[i]);
                    begin = Math.min(begin, w.min);
                    end = Math.max(end, w.max);
                }
            }
    
            if (begin != Integer.MAX_VALUE) {
                return (end - begin) + 1;
            }
            return 0;
        }
    
        public void put(String[] dw) {
    
            for (int i = 0; i < dw.length; i++) {
                if (!st.contains(dw[i])) {
                    st.put(dw[i], new Words(i));
                }
                else {
                    Words w = st.get(dw[i]);
                    w.min = Math.min(w.min, i);
                    w.max = Math.max(w.max, i);
                }
            }
        }
    
        public static void main(String[] args) {
    
            // TODO Auto-generated method stub
            DicMN dic = new DicMN();
            String[] arr1 = { "one", "two", "three", "four", "five", "six", "seven", "eight" };
            dic.put(arr1);
            String[] arr2 = { "two", "five" };
            System.out.print("Interval:" + dic.findMinInterval(arr2));
        }
    }
    

提交回复
热议问题