Easy JAVA O(n) solution


  • 0
    I

    The idea is to traverse s and t from the last character in each string. If the two character are the same, we move the indexes in both s and t one step toward 0, if not, we just move the index in t one step toward 0.

    public class Solution {
        public boolean isSubsequence(String s, String t) {
            
            if (s == null || t == null) {
                return false;
            }
            if (s.length() == 0) {
                return true;
            }
            int index = s.length() - 1;
            for (int i = t.length() - 1; i >= 0; i--) {
                if (t.charAt(i) == s.charAt(index)) {
                    index--;
                }
                if (index < 0) {
                    break;
                }
            }
            return index < 0;
        }
    }
    

Log in to reply
 

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