![]() |
VOOZH | about |
Given a stringS, the task is to check if the string target is a subsequence of string S or not, using a Stack.
Examples:
Input: S = ”KOTTAYAM”, target = ”KOTA”
Output: Yes
Explanation: “KOTA” is a subsequence of “KOTTAYAM”.Input: S = ”GEEKSFORGEEKS”, target =”FORFOR”
Output: No
Approach: Follow the steps to solve the problem:
Below is the implementation of the above approach:
Yes
Time Complexity : O(N)
Auxiliary Space : O(N)
Approach 2: Using the find() function
Another approach to check if a string is a subsequence of another string is to use the find() function. We can call find() on the second string to find the index of the first occurrence of the first character of the first string. Then, we can iterate over the first string and call find() on the second string with the starting index set to the index of the previous character plus one. If find() returns string::npos, it means that the current character in the first string is not present in the second string and hence the first string is not a subsequence of the second string.
Define a function that takes two string arguments s1 and s2.
Initialize an integer variable index to -1. This will be used to keep track of the starting index for each find() call.
Iterate over each character c in s1 using a range-based for loop.
Call the find() function on s2 with the arguments c and index + 1. The second argument specifies the starting index for the search, which is the index of the previous character plus one.
If find() returns string::npos, which indicates that the character was not found in s2, return false immediately, as s1 is not a subsequence of s2.
If find() returns a valid index, update index to the returned value.
After iterating over all the characters in s1, return true, as s1 is a subsequence of s2.
yes
Time Complexity : O(M*N)
Auxiliary Space : O(1)