Answer to Question #256513 in Python for rasi

Question #256513

 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


1
Expert's answer
2021-11-05T07:25:35-0400
# 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)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS