-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsSubsequence.java
More file actions
28 lines (24 loc) · 877 Bytes
/
IsSubsequence.java
File metadata and controls
28 lines (24 loc) · 877 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public boolean isSubsequence(String s, String t) {
int sLength = s.length();
int tLength = t.length();
// Edge case: if s is empty, it's always a subsequence
if (sLength == 0) {
return true;
}
int sIndex = 0; // Pointer for string s
// Iterate through string t
for (int tIndex = 0; tIndex < tLength; tIndex++) {
// If characters match, move the pointer for s
if (sIndex < sLength && s.charAt(sIndex) == t.charAt(tIndex)) {
sIndex++;
}
// If we've matched all characters of s, return true
if (sIndex == sLength) {
return true;
}
}
// If we finish iterating through t and haven't matched all of s
return false;
}
}