Is Subsequence Problem


Description

LeetCode Problem 392.

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).

Example 1:

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

Example 2:

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

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 10^4
  • s and t consist only of lowercase English letters.


Sample C++ Code

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
class Solution {
public:
    bool isSubsequence(string s, string t) {
        int m = s.size();
        int n = t.size();
        int dp[m + 1][n + 1];
        
        for (int i = 0; i <= m; i ++) {
            for (int j = 0; j <= n; j ++) {
                dp[i][j] = 0;
            }
        }
        
        for (int i = 0; i < m; i ++) {
            for (int j = 0; j < n; j ++) {
                if (s[i] == t[j]) {
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                } else {
                    dp[i + 1][j + 1] = dp[i + 1][j];
                }
            }
        }
                
        return (dp[m][n] == m);
    }
};




Related Posts

Palindromic Substrings Problem

LeetCode 647. Given a string s, return the number of...

Largest Plus Sign Problem

LeetCode 764. You are given an integer n. You have...

K Inverse Pairs Array Problem

LeetCode 629. For an integer array nums, an inverse pair...

Domino And Tromino Tiling Problem

LeetCode 790. You have two types of tiles, a 2...

Decode Ways II Problem

LeetCode 639. A message containing letters from A-Z can be...