Is Subsequence
Given a string s and a string t, check if s is subsequence of t.
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).
Solution
We traverse both strings from one side to other side. If a matching character is found, we move ahead in both strings. Otherwise we move ahead only in second string.
fun isSubsequence(s: String, t: String): Boolean {
if (s.isEmpty())
return true
if (t.isEmpty())
return false
var i = 0
for (element in t) {
if (s[i] == element) {
i++
if (i == s.length)
return true
}
}
return false
}