본문 바로가기

알고리즘 스터디

[Leetcode/파이썬] 392. Is Subsequence

반응형

Is Subsequence

Difficulty: Easy


Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

 

Example 1:

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

Example 2:

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

 

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 104
  • s and t consist only of lowercase English letters.

 

Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?

 

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

        if len(s) > len(t) :
            return False

        if len(s) == len(t) and s != t :
            return False
        elif s == t :
            return True


        s_idx = t_idx = 0

        while s_idx != len(s) and t_idx != len(t) :
            if s[s_idx] == t[t_idx] :
                s_idx += 1

            t_idx += 1

        if s_idx == len(s) :
            return True
        else :
            return False

전에도 풀었던 문제인데 거의 비슷하게 풀었다. 그러나 이번엔 좀 지저분하게 풀었다. 왜 이렇게 풀렸지..? 

여러가지 상황을 다 고려했다. 제한사항에 s, t 의 길이들이 0부터 시작하는 것을 보고 어차피 t 야 s 보다 작으면 false 를 뱉어내야 하니까 s 의 길이만 고려하였다. 

포인터 옮기는거는 많이 해봤으니까 while 문과 같이 작성하면 되고, 조건을 두 문장 중 먼저 끝에 도달하는 게 생기면 멈추는 조건으로 작성하였다. 

그리고 s가 모두 검색되었다면 True, 아니라면 False를 반환한다 까지가 풀이이다. 

Follow UP은 무엇을 말하고 싶은걸까..? 이것도 좀 궁금하네.

반응형