"Determining if a String is a Subsequence of Another String - Problem Solution"
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).
Example Usage :
Let's consider a few examples to understand how the IsSubsequence method works :
Example 1 :
Input : s = "abc", t = "ahbgdc"
Output : true
Example 1 :
Input : s = "axc", t = "ahbgdc"
Output : false
Solution Overview : 🧾
To solve this problem, we can use a simple algorithm:
1. Iterate through each character in s.
2. For each character, check if it exists in t.
3. If it exists, find its position in t using IndexOf and update t to be the substring starting from the position after the found character.
4. Repeat this process until all characters in s are found in t.
5. If the count of found characters equals the length of s, return true; otherwise, return false.
Implementation in C# :
public class Solution
{
public bool IsSubsequence(string s, string t)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (t.Contains(s[i]))
{
int position = t.IndexOf(s[i]);
t = t.Substring(position + 1);
count++;
}
}
return count == s.Length ? true : false;
}
}
Example Usage :
Provide examples using the IsSubsequence method with sample input strings s and t and expected output.
0 Comments