題目
給定字元串 s 和 t ,判斷 s 是否為 t 的子序列。
你可以認為 s 和 t 中僅包含英文小寫字母。字元串 t 可能會很長(長度 ~= 500,000),而 s 是個短字元串(長度 <=100)。
字元串的一個子序列是原始字元串删除一些(也可以不删除)字元而不改變剩餘字元相對位置形成的新字元串。(例如,"ace"是"abcde"的一個子序列,而"aec"不是)。
示例 1:
s = "abc", t = "ahbgdc"
傳回 true.
示例 2:
s = "axc", t = "ahbgdc"
傳回 false.
後續挑戰 :
如果有大量輸入的 S,稱作S1, S2, ... , Sk 其中 k >= 10億,你需要依次檢查它們是否為 T 的子序列。在這種情況下,你會怎樣改變代碼?
解題思路
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
# #雙指針
# sList = list(s)
# tList = list(t)
# if len(sList) <= 0:return True
# if len(tList) <= 0:return False
# sIndex = 0
# # tIndex = 0
# for i in tList:
# if i == sList[sIndex]:
# sIndex = sIndex + 1
# if sIndex == len(s):
# return True
# return False
#動态規劃,對t進行預處理,形成一個二維數組,記錄每個字母的下一個位置
# t = " "+t
sLen, tLen = len(s), len(t)
#預處理
dp = [[-1]*26 for _ in range(tLen+1)]
# dp.append([-1]*26)
for i in range(tLen-1,-1,-1):
ordChar = ord(t[i]) - 97
for j in range(26):
dp[i][j] = i if j == ordChar else dp[i+1][j]
print(dp)
#進行搜尋定位
nextIndex = 0
for j in s:
ordChar = ord(j) - 97
if dp[nextIndex][ordChar] == -1:return False
nextIndex = dp[nextIndex][ordChar] + 1
print("ord:{} nextindex:{}".format(ordChar, nextIndex))
return True