792. Number of Matching Subsequences

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 in words that are a subsequence of S: "a", "acd", "ace".

Note:

  • All words in words and S 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;
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值