38. How do you check if a string contains a subsequence? - Link
Example: Str-1 = “XAY”, Str-2= “XYAXAYZAX” string 1 is present in a substring of string 2 i.e XAY is present in XYAXAYZAX
# Function to check if target
# is a subsequence of string S
def checkforSubsequence(S, target):
# Declare a stack
s = []
# Push the characters of
# target into the stack
for i in range(len(target)):
s.append(target[i])
# Traverse the string S in reverse
for i in range(len(S) - 1, -1, -1):
# If the stack is empty
if (len(s) == 0):
print("Yes")
return
# If S[i] is same as the
# top of the stack
if (S[i] == s[-1]):
# Pop the top of stack
s.pop()
# Stack s is empty
if (len(s) == 0):
print("Yes")
else:
print("No")
# Driver Code
if __name__ == "__main__":
S = "XYAXAYZAX"
target = "XAY"
checkforSubsequence(S, target)
Comments
Leave a comment