Subsequence.java


Below is the syntax highlighted version of Subsequence.java from §5 Strings.


/******************************************************************************
 *  Compilation:  javac Subsequence.java
 *  Execution:    java Subsequence s t
 *  Dependencies: StdOut.java
 *  
 *  Determines whether string s is a subsequence of string t.
 *
 *
 ******************************************************************************/


public class Subsequence {

    // is the string s a subsequence of the string t?
    public static boolean isSubsequence(String s, String t) {
        int m = s.length();
        int n = t.length();
        if (m == 0) return true;

        int i = 0;
        for (int j = 0; j < n; j++) {
            if (s.charAt(i) == t.charAt(j)) i++;
            if (i == m) return true;
        }
        return false;
    }

    public static void main(String[] args) { 
        String s = args[0];
        String t = args[1];
        StdOut.println(isSubsequence(s, t));
    }

}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 12:50:46 EDT 2017.