simple java code with explanation


  • 0
    M

    Two pointers method, pointer i just scan each character in string t , point j increase by one once we find a matching character, when the pointer j reach the end of the string s, we had found every character of s in string t, thus found a subsequence.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.