Is Subsequence In String

 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:


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

Output: true

Example 2:


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

Output: false

 


Approach 1: - 2 Pointer


class Solution {
    public boolean isSubsequence(String s, String t) {
       
        int i=0,j=0;
       

        while(i< s.length() && j<t.length())
        {
            if(s.charAt(i)==t.charAt(j))
            {
                i++;
                j++;
            }
            else
            {
                j++;
            }
        }
        return i==s.length();

   
    }
}



Approach 2: Recurssion DP


class Solution {
    public boolean isSubsequence(String s, String t) {
        Boolean[][] memo = new Boolean[s.length()+1][t.length()+1];
        return dfs(s, t, 0, 0, memo);
    }

    private boolean dfs(String s, String t, int i, int j, Boolean[][] memo) {
        if (i == s.length()) return true;  // all chars in s matched
        if (j == t.length()) return false; // t ended but s not finished

        if (memo[i][j] != null) return memo[i][j];

        if (s.charAt(i) == t.charAt(j)) {
            memo[i][j] = dfs(s, t, i+1, j+1, memo);
        } else {
            memo[i][j] = dfs(s, t, i, j+1, memo);
        }
        return memo[i][j];
    }
}



Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence