lc792. Number of Matching Subsequences

231 阅读1分钟
  1. Number of Matching Subsequences Medium

546

43

Favorite

Share Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

Example : Input: S = "abacde" 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].

思路:用字典保存S字符串每个字符出现下标,例子:dic['a']=[0,2],dic['b']=[1] 然后遍历words,置标示位pre=-1,遍历每个字符c,到相应的dic[c]中查找最近的位置,各种判断。。。

代码:python3

class Solution:
    def numMatchingSubseq(self, S: str, words) -> int:
        dic = {}
        for (index,value) in enumerate(S):
            if value in dic.keys():
                dic[value].append(index)
            else:
                dic[value] = [index]
        print(words)
        delList = []
        for word in words:
            pre = -1
            print("start "+word)
            needJump = False
            for (index,value) in enumerate(word):
                if needJump == True:
                    needJump = False
                    break
                if value not in dic.keys():
                    delList.append(word)
                    needJump = True
                    continue
                b = False
                for index in dic[value]:
                    if index > pre:
                        b = True
                        pre = index
                        break
                if b == False:
                    if word in words:
                        delList.append(word)
                        needJump = True
                        break
        print(delList)
        return len(words)-len(delList)
if __name__ == '__main__':
    print(Solution().numMatchingSubseq("dcoegauiqk",["dco","coegauiq","ehqyopnqgm","wtqbgozlae"]))