DEV Community

shine
shine

Posted on

[📝LeetCode #392] Is Subsequence

🎀 The Problem

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:

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

👩‍💻 My Answer

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

        if (s.length() == 0)
            return true;

        for (int i = 0; i < t.length(); i++) {
            if (s.charAt(current) == t.charAt(i)) {
                current++;
            }

            if (current == s.length())
                return true;
        }

        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime & Memory

Pro & Con

  • ✖️ Runtime & Memory

💋 Ideal Answer

Approach

I don't really find the better one in the LeetCode solution, but I just find that it is useful to set the return return current == s.length();.

New Code

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

        for (int i = 0; i < t.length() && current < s.length(); i++) {
            if (s.charAt(current) == t.charAt(i)) {
                current++;
            }
        }

        return current == s.length();
    }
}
Enter fullscreen mode Exit fullscreen mode

This only beats 66% but I don't think there is a better version of this in Java.

💡 What I Learned

  • I started to code faster and gain more knowledge of the library.

Top comments (0)