LeetCode - Algorithms - 392. Is Subsequence

Problem

392. Is Subsequence

Java

Recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isSubsequence(String s, String t) {
boolean b = true;
final int len_s = s.length();
if (len_s > 0) {
int i = t.indexOf(s.charAt(0));
if (i != -1)
return isSubsequence(s.substring(1), t.substring(++i));
else
return false;
}
return b;
}
}

Submission Detail

  • 15 / 15 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Is Subsequence.
  • Memory Usage: 37.5 MB, less than 62.77% of Java online submissions for Is Subsequence.

Iterative

© JAVA clean, quick, concise solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isSubsequence(String s, String t) {
final int len_s = s.length();
final int len_t = t.length();
if (len_s > len_t)
return false;
int i = 0;
for (int j = 0; j < len_t && i < len_s; ) {
if (s.charAt(i) == t.charAt(j)) i++;
j++;
}
return i >= len_s;
}
}

Submission Detail

  • 15 / 15 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Is Subsequence.
  • Memory Usage: 37.1 MB, less than 39.06% of Java online submissions for Is Subsequence.