題目:
判斷子序列:給定字符串 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 的子序列。在這種情況下,你會怎樣改變代碼?
致謝:
特別感謝 @pbrother?添加此問題并且創建所有測試用例。
思路:
雙指針,較簡單。
程序:
class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s and t:
return True
if s and not t:
return False
if not s and not t:
return True
index1 = 0
index2 = 0
counter = 0
while index1 < len(s) and index2 < len(t):
if s[index1] == t[index2]:
index1 += 1
counter += 1
index2 += 1
if counter == len(s):
return True
else:
return False