코-딩/Leetcode

[leetcode] 392. Is Subsequence(python)

힞뚜루마뚜루 2023. 1. 22. 15:31
728x90

문제 : https://leetcode.com/problems/is-subsequence/description/

난이도 : Easy

 

문자열 s가 t에 포함되어 있는지 찾는 문제다.

어떻게 할까 고민하다가 그냥 찾으면 그 위치부터 자르고, 찾으면 자르고 단순하게 풀기로 했다. (늘 그랬음;;)

 

풀이1
class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        answer = False
        tIdx, sIdx = 0, 0

        if len(s) > len(t):
            return False
            
        if len(s) == 0:
            return True
    
        while len(t) > 0 and tIdx > -1:
            tIdx = t.find(s[sIdx])
            if(tIdx > -1):      # 존재하면
                t = t[tIdx + 1:]
                sIdx += 1
            if len(s) == sIdx:
                answer = True
                break
        
        return answer

 

풀이2
class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        i, j  = 0, 0

        while i < len(s) and j < len(t):
            if s[i] == t[j]:
                i += 1
            j += 1
    
        return i == len(s)

투 포인터 개념(거창하게..)으로 풀 수도 있다.

728x90