작심삼일

[LeetCode] 392 | Is Subsequence | Python 본문

스터디/코테

[LeetCode] 392 | Is Subsequence | Python

yun_s 2022. 3. 2. 10:15
728x90
반응형

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


문제

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).


조건

  • 0 <= s.length <= 100
  • 0 <= t.length <= $10^4$
  • s and t consist only of lowercase English letters.

내 풀이

s가 ''이 되면 항상 True고, t가 ''이 되면 항상 False다.

위 두가지 상황에 포함되지 않으면 이제 아래 알고리즘을 진행한다.

 

t를 차례로 한글자씩 보면서 그것이 현재 s의 글자와 일치하지 않으면 다음 t의 글자와 비교하고, 일치한다면 s의 다음 글자와 비교한다.

이를 끝까지 반복하면서 s의 끝글자까지 일치하는 것을 찾으면 True, 그렇지 못한다면 False다.


코드

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        if s == '': return True
        if t == '': return False
        n = 0
        for subt in t:
            if s[n] == subt:
                n += 1
            
                if n == len(s):
                    return True
        
        return False
728x90
반응형
Comments