Easy to understand java solution


  • 0
    M
    class Solution {
        public boolean isSubsequence(String s, String t) {
            if(s==null || t==null){
                return false;
            }
            if(s.equals("")){
                // because empty string is sub string of all the strings
                return true;
            }
            if(s.length()>t.length()){
                return false;
            }
            // variable to keep track of character of s
            int k =0;
    
            for (int i=0;i<t.length();i++){
                if(s.charAt(k) == t.charAt(i)){
                    // increase the k after each character match to take next character into consideration
                    k = k+1;
                    if(k==s.length()){
                        // this means we have iterated over all characters of s successfully, so we should return true
                        return true;
                     }
                }
            }
            // this means we have iterated over all characters of p but not of s, so we should return false
            return false;
            
        }
    }
    

Log in to reply
 

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