Skip to content

Commit 7ee4e90

Browse files
committed
O(n) time and O(1) space using extra variable
1 parent 62ae2f0 commit 7ee4e90

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
Given a string s and a string t, check if s is subsequence of t.
3+
4+
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
5+
6+
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).
7+
8+
Example 1:
9+
s = "abc", t = "ahbgdc"
10+
11+
Return true.
12+
13+
Example 2:
14+
s = "axc", t = "ahbgdc"
15+
16+
Return false.
17+
18+
Follow up:
19+
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
20+
"""
21+
class Solution:
22+
def isSubsequence(self, s: str, t: str) -> bool:
23+
if not s and t:
24+
return True
25+
if s and not t:
26+
return False
27+
if not s and not t:
28+
return True
29+
list_t = list(t)
30+
count = 0
31+
for i,char in enumerate(t):
32+
if char == s[count]:
33+
count += 1
34+
if count >= len(s):
35+
return True
36+
return count == len(s)

0 commit comments

Comments
 (0)