Given string S
and a dictionary of words words
, find the number of words[i]
that is a subsequence of S
.
Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: There are three words inwords
that are a subsequence ofS
: "a", "acd", "ace".
Note:
- All words in
words
andS
will only consists of lowercase letters. - The length of
S
will be in the range of[1, 50000]
. - The length of
words
will be in the range of[1, 5000]
. - The length of
words[i]
will be in the range of[1, 50]
.
思路:如果只要比较2个string是不是subsequence,暴力的方法也是最佳的方法,因为肯定至少都要各遍历一遍
如果是一个string A与另外一个list of string BS呢?一个个比?那肯定要把比过的信息记录下来,比如A与Bs[0]比较的时候,哪些组合是无法构成sub sequence关系的,哪些是能构成的,放到HashMap里面
当然也有另外一种思路,就是先对Bs做预处理,
from collections import defaultdict
from bisect import bisect_left
class Solution:
def numMatchingSubseq(self, S, words):
"""
:type S: str
:type words: List[str]
:rtype: int
"""
d = defaultdict(list)
for i in range(len(S)): d[S[i]].append(i)
res = 0
for w in words:
si, wi = 0, 0
while wi<len(w):
l = d[w[wi]]
t = bisect_left(l, si)
if t == len(l): break
wi += 1
si = l[t]+1
if wi==len(w): res+=1
return res
#print(bisect_left([1,2,3], 4))
s=Solution()
print(s.numMatchingSubseq(S = "abcde", words = ["a", "bb", "acd", "ace"]))
class Solution {
public int numMatchingSubseq(String S, String[] words) {
int n=S.length();
int[][] next= new int[n+1][26];
char[] sc= S.toCharArray();
Arrays.fill(next[n],-1);
for(int i=n-1;i>=0;i--){
for(int j=0;j<26;j++){
next[i][j]=next[i+1][j];
}
next[i][sc[i]-'a']=i+1;
}
int res=0;
for(int i=0;i<words.length;i++){
if(isSubseq(next,words[i])) res++;
}
return res;
}
public boolean isSubseq(int[][] next,String s){
char[] sc= s.toCharArray();
int j=0;
for(int i=0;i<sc.length;i++){
char c= sc[i];
if(next[j][c-'a']>-1) j=next[j][c-'a'];
else return false;
}
return true;
}
}