class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
mapping = dict()
for i, char in enumerate(t):
if char in mapping:
mapping[char].append(i)
else:
mapping[char] = [i]
current = -1
for char in s:
if char not in mapping:
return False
indices = mapping[char]
target = current + 1
left, right = 0, len(indices) - 1
while left <= right:
mid = (left + right) // 2
if indices[mid] == target:
right = mid - 1
elif indices[mid] > target:
right = mid - 1
elif indices[mid] < target:
left = mid + 1
if left == len(indices):
return False
else:
current = indices[left]
return True
后续挑战的答案:
class Solution:
def single_match(self, s, mapping):
current = -1
for char in s:
if char not in mapping:
return False
indices = mapping[char]
target = current + 1
left, right = 0, len(indices) - 1
while left <= right:
mid = (left + right) // 2
if indices[mid] == target:
right = mid - 1
elif indices[mid] > target:
right = mid - 1
elif indices[mid] < target:
left = mid + 1
if left == len(indices):
return False
else:
current = indices[left]
return True
def numMatchingSubseq(self, S: str, words: List[str]) -> int:
mapping = dict()
for i, char in enumerate(S):
if char in mapping:
mapping[char].append(i)
else:
mapping[char] = [i]
return len([1 for s in words if self.single_match(s, mapping)])