LeetCode 75

Is Subsequence

Problem
LC 392
Topic
Two Pointers
File
official75_LC392IsSubsequence.java
Path
pkg5leetcode/official75/official75_LC392IsSubsequence.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC392IsSubsequence.java
Approach
Two pointers match chars of t in s.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC392IsSubsequence.java
1package pkg5leetcode.official75;2 3/*4 * Is Subsequence | LC 3925 * APPROACH: Two pointers match chars of t in s.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC392IsSubsequence {9    static boolean isSubsequence(String s, String t) {10        int i = 0;11        for (int j = 0; j < t.length() && i < s.length(); j++)12            if (s.charAt(i) == t.charAt(j)) i++;13        return i == s.length();14    }15 16    public static void main(String[] args) {17        check(isSubsequence("abc", "ahbgdc"), "case1");18        check(!isSubsequence("axc", "ahbgdc"), "case2");19        System.out.println("all tests passed");20    }21 22    static void check(boolean cond, String name) {23        if (!cond) throw new AssertionError("FAILED: " + name);24        System.out.println("  PASS " + name);25    }26}