File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * Author: Minho Kim (ISKU)
3
+ * Date: November 8, 2019
4
+ * E-mail: minho.kim093@gmail.com
5
+ *
6
+ * https://github.com/ISKU/Algorithm
7
+ * https://leetcode.com/problems/number-of-matching-subsequences/
8
+ */
9
+
10
+ class Solution {
11
+
12
+ public int numMatchingSubseq (String S , String [] words ) {
13
+ List <Integer >[] letters = new ArrayList [26 ];
14
+ for (int i = 0 ; i < 26 ; i ++)
15
+ letters [i ] = new ArrayList <Integer >() {{ add (-1 ); }};
16
+ for (int i = 0 ; i < S .length (); i ++)
17
+ letters [S .charAt (i ) - 'a' ].add (i );
18
+
19
+ int answer = 0 ;
20
+ for (String word : words ) {
21
+ boolean contains = true ;
22
+ int index = 0 ;
23
+
24
+ for (int i = 0 ; i < word .length (); i ++) {
25
+ List <Integer > indexes = letters [word .charAt (i ) - 'a' ];
26
+ int next = lowerBound (indexes , index );
27
+ if (next == -1 ) {
28
+ contains = false ;
29
+ break ;
30
+ }
31
+
32
+ index = indexes .get (next ) + 1 ;
33
+ }
34
+
35
+ if (contains )
36
+ answer ++;
37
+ }
38
+
39
+ return answer ;
40
+ }
41
+
42
+ private int lowerBound (List <Integer > array , int target ) {
43
+ int l = 0 ;
44
+ int r = array .size () - 1 ;
45
+
46
+ while (l < r ) {
47
+ int mid = (l + r ) / 2 ;
48
+
49
+ if (array .get (mid ) < target )
50
+ l = mid + 1 ;
51
+ else
52
+ r = mid ;
53
+ }
54
+
55
+ return array .get (l ) < target ? -1 : l ;
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments