Skip to content

Commit 9c9b034

Browse files
committed
LeetCode #792: Number of Matching Subsequences
1 parent 878ce94 commit 9c9b034

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

LeetCode/792/Solution.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
}

0 commit comments

Comments
 (0)