LeetCode 392. Is Subsequence

題目:

給兩個string s跟t,check if s is a subsequence of t。(順序不能變)

返回true or false

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

思路:

  1. 先看s是否存在,如果不存在,那s就會是所有t的subsequence
    if not s:
    return True
  2. 首先需要知道s長度多少確保可以go through整個s
    len_s = len(s)
  3. 接著換go through string t 的每個字母 要對應string s中的字母是否相同
    i=0 意思是從s的第一個字母開始比較
    for char in t:
    if char = s[i]:
    i += 1 (有對應到字母則i+1比較下一個字母)
    if i == len_s:
    意思是已經找到所有s在t裡面的字母,
    return True
  4. return False

Coding:

class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s :
return True

len_s = len(s)
i=0

for char in t:
if char == s[i]:
i+=1
if i == len_s:
return True
return False

--

--

Sharko Shen
Data Science & LeetCode for Kindergarten

Thinking “Data Science for Beginners” too hard for you? Check out “Data Science for Kindergarten” !