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).
Input: s = "abc", t = "ahbgdc"
Output: true
Input: s = "axc", t = "ahbgdc"
Output: false
0 <= s.length <= 100
0 <= t.length <= 10^4
s
and t
consist only of lowercase English letters.s
is an empty string?
true
.t
is an empty string but s
is not?
t
is empty and s
is not, the function should return false
.t
using a pointer j
.t
, if it matches the current character in s
pointed by the pointer i
, move the pointer i
to the next character in s
.i
reaches the end of s
, this means all characters of s
were found in sequence within t
, hence return true
.t
without i
reaching the end of s
, return false
.public class Solution {
public boolean isSubsequence(String s, String t) {
if (s.length() == 0) return true;
int i = 0;
for (int j = 0; j < t.length(); j++) {
if (s.charAt(i) == t.charAt(j)) {
i++;
if (i == s.length()) {
return true;
}
}
}
return false;
}
}
t
. We are iterating through t
once.This ensures that the algorithm is efficient even with the maximum constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?