classSolution:defisSubsequence(self,s:str,t:str) ->bool: mapping =dict()for i, char inenumerate(t):if char in mapping: mapping[char].append(i)else: mapping[char]= [i] current =-1for char in s:if char notin mapping:returnFalse indices = mapping[char] target = current +1 left, right =0,len(indices)-1while left <= right: mid = (left + right) //2if indices[mid]== target: right = mid -1elif indices[mid]> target: right = mid -1elif indices[mid]< target: left = mid +1if left ==len(indices):returnFalseelse: current = indices[left]returnTrue
后续挑战的答案:
classSolution:defsingle_match(self,s,mapping): current =-1for char in s:if char notin mapping:returnFalse indices = mapping[char] target = current +1 left, right =0,len(indices)-1while left <= right: mid = (left + right) //2if indices[mid]== target: right = mid -1elif indices[mid]> target: right = mid -1elif indices[mid]< target: left = mid +1if left ==len(indices):returnFalseelse: current = indices[left]returnTruedefnumMatchingSubseq(self,S:str,words: List[str]) ->int: mapping =dict()for i, char inenumerate(S):if char in mapping: mapping[char].append(i)else: mapping[char]= [i]returnlen([1for s in words if self.single_match(s, mapping)])