Leetcode

392. Is Subsequence

YGSEO 2020. 8. 15. 15:34
728x90
class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        i=0
        j=0
        while(j<len(t) and i<len(s)):
            if(s[i] == t[j]):
                i+=1
                j+=1
            else:
                j+=1
        if(i==len(s)):
            return True
        return False

출처: leetcode.com/problems/is-subsequence/discuss/769405/Elegant-Python-solution-91-without-using-DP-simple-to-understand-O(n)

 

s가 찾고자 하는 alphabet, t가 대상 string

1. while 반복문으로 각 string s, t의 len까지 반복

2. s와 t의 element를 비교하면서 loop대신 t의 j-th element가 s에 없다면 하나씩 move(else 문) 있다면, if문에서 i +=1해서 i로 counting

3. i와 s의 len이 같다면 s의 모든 element가 t에 있다는게 count되기 때문에 True 리턴, 아닐경우 False 리턴

 

728x90