classSolution: defisSubsequence(self, s, t): indices = collections.defaultdict(list) for i, ch in enumerate(t): indices[ch].append(i)
prev = -1 for i in range(len(s)): if s[i] notin indices: returnFalse idx = self.bSearch(prev, indices[s[i]]) if idx == -1: returnFalse prev = idx returnTrue
defbSearch(self, prev, nums): if prev >= nums[-1]: return-1
start, end = 0, len(nums) - 1 while start < end: mid = start + (end - start) // 2 if nums[mid] > prev: # Mistake2 : we should find greater than previous index CANNOT equal end = mid else: start = mid + 1
return nums[start] if nums[start] > prev else-1 # Mistake1 : forget to consider the index may not in the nums!!!
classSolution: defnumMatchingSubseq(self, S, words): # Time O(n) indices = [[] for _ in range(26)] for i, ch in enumerate(S): indices[ord(ch)-ord('a')].append(i)
cnt = 0 mdic = {} for word in words: if word in mdic: cnt += mdic[word] continue
# Time : O(mlog n) n is the length of S, m is the length of word defisMatch(self, indices, word): prev = -1 for ch in word: idx = self.bSearch(prev, indices[ord(ch)-ord('a')]) if idx == -1: returnFalse prev = idx returnTrue
defbSearch(self, prev, nums): ifnot nums or prev >= nums[-1]: return-1
start, end = 0, len(nums) - 1 while start < end: mid = start + (end - start) // 2 if nums[mid] > prev: end = mid else: start = mid + 1 return nums[start] if nums[start] > prev else-1
classSolution: defnumMatchingSubseq(self, S, words): indices = [[] for _ in range(26)] for word in words: indices[ord(word[0]) - ord('a')].append(word[1:])
cnt = 0 for ch in S: cans = indices[ord(ch)-ord('a')] newCans = [] for can in cans: if len(can) == 0: cnt += 1 continue if can[0] == ch: newCans.append(can[1:]) else: indices[ord(can[0])-ord('a')].append(can[1:]) indices[ord(ch)-ord('a')] = newCans return cnt
classSolution(object): defminWindow(self, S, T): n = len(S) # Must be the start index of the results!!! cur = [i if S[i] == T[0] else-1for i in range(n)]
for j in xrange(1, len(T)): last = -1 new = [-1] * n for i, ch in enumerate(S): if last >= 0and ch == T[j]: new[i] = last if cur[i] >= 0: last = cur[i] cur = new
start, end = 0, n for e, s in enumerate(cur): if s >= 0and e - s < end - start: start, end = s, e return S[start:end+1] if end != n else""