LeetCode 392. Is Subsequence

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        t_index = -1
        flag = False

        if len(s) == 0:
            return True
        elif len(t) == 0 or len(s)>len(t):
            return False

        for s_index in range(len(s)):
            t_index += 1
            if t_index >= len(t):
                return False
            while s[s_index] != t[t_index]:
                t_index += 1
                if t_index >= len(t):
                    return False
            
        return True
        
class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        s_index = 0
        t_index = 0
        while s_index<len(s) and t_index<len(t):
            if s[s_index] == t[t_index]:
                s_index += 1
            t_index += 1
            
        if s_index == len(s):
            return True
        return False

for文やwhile文を入れ子構造にするとindexの管理が難しくなるので、whileを一つにまとめられるならその方が良い。

時間計算量:O(min(len(s), len(t)))
→while文はsかtのindexが超えない範囲で回るのでsかtの短い方分だけ回る
空間計算量:O(len(s)+len(t))
→sとtだけをいじっている。他の変数は全部定数なので。