package leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * https://leetcode.com/problems/number-of-matching-subsequences/
 */
public class Problem792 {
    public int numMatchingSubseq(String S, String[] words) {
        int result = 0;
        Map<Character, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if (!map.containsKey(c)) {
                List<Integer> list = new ArrayList<>();
                list.add(i);
                map.put(c, list);
            } else {
                map.get(c).add(i);
            }
        }

        for (String word : words) {
            int lastIndex = 0;
            boolean found = true;
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if (!map.containsKey(c)) {
                    found = false;
                    break;
                }
                List<Integer> indices = map.get(c);
                int index = Collections.binarySearch(indices, lastIndex);
                if (index < 0) {
                    index = (-(index) - 1);
                    if (index >= S.length()) {
                        found = false;
                        break;
                    }
                }
                lastIndex = index;
            }

            if (found) {
                result++;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Problem792 prob = new Problem792();
        System.out.println(prob.numMatchingSubseq("abcde", new String[]{"a", "bb", "acd", "ace"})); // 3
    }
}

@@ -760,19 +760,19 @@
     int 
-las
+nex
 tIndex =
@@ -772,17 +772,18 @@
 Index = 
-0
+-1
 ;%0A      
@@ -1080,16 +1080,155 @@
 get(c);%0A
+                if (nextIndex == -1) %7B%0A                    nextIndex = indices.get(0) + 1;%0A                    continue;%0A                %7D%0A
         
@@ -1281,19 +1281,19 @@
 ndices, 
-las
+nex
 tIndex);
@@ -1348,19 +1348,27 @@
       in
-dex
+t insertion
  = (-(in
@@ -1408,23 +1408,31 @@
  (in
-dex %3E= S.length
+sertion %3E= indices.size
 ()) 
@@ -1545,44 +1545,150 @@
     
-%7D%0A                lastIndex = index;
+    nextIndex = indices.get(insertion) + 1;%0A                %7D else %7B%0A                    nextIndex = indices.get(index) + 1;%0A                %7D
 %0A   
@@ -1766,33 +1766,32 @@
     %7D%0A        %7D%0A
-%0A
         return r
@@ -1806,208 +1806,7 @@
    %7D
-%0A%0A    public static void main(String%5B%5D args) %7B%0A        Problem792 prob = new Problem792();%0A        System.out.println(prob.numMatchingSubseq(%22abcde%22, new String%5B%5D%7B%22a%22, %22bb%22, %22acd%22, %22ace%22%7D)); // 3%0A    %7D
 %0A%7D%0A

Solve problem 792