392. Is Subsequence & 792. Number of Matching Subsequences

392. Is Subsequencearrow-up-right

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

Constraints:

  • 0 <= s.length <= 100

  • 0 <= t.length <= 104

  • s and t consist only of lowercase English letters.

My Solutions:

class Solution {
    public boolean isSubsequence(String s, String t) {
        if (s.length() == 0) return true;
        if (s.length() > t.length()) return false;
        int index = 0;
        for (int i = 0; i < t.length(); i++) {
            if (s.charAt(index) == t.charAt(i)) {
                index++;
                if (index == s.length()) return true;
            } 
        }
        return index == s.length();
    }
}

Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?

792. Number of Matching Subsequencesarrow-up-right

Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

Example 1:

Example 2:

Constraints:

  • 1 <= s.length <= 5 * 104

  • 1 <= words.length <= 5000

  • 1 <= words[i].length <= 50

  • s and words[i] consist of only lowercase English letters.

My Solutions:

Last updated