A slightly modified answer based on @ruakh's solution:
public static boolean containsSubsequence(final String sequence, final String subsequence) { if (Objects.requireNonNull(sequence).isEmpty() || Objects.requireNonNull(subsequence).isEmpty() || subsequence.length() > sequence.length()) { return false; } int index = 0; for (int i = 0; i < sequence.length(); i++) { if (sequence.charAt(i) == subsequence.charAt(index) && ++index == subsequence.length()) { return true; } } return false; }
Objects.requireNonNull() from Java 7, do not forget to replace something like this (from Apache Commons StringUtils ?) If you are not in Java 7. Assumes that returning false is suitable for an empty sequence or subsequence, or you may want to throw something- something like IllegalArgumentException .
Two if were combined into a single sentence for compactness.
edit: If someone is mathematically inclined or after the original @ruakh solution, any sequence should contain an empty subsequence. The only reason why my code above does it differently is because I prefer to represent an empty argument as a form of an invalid argument, thereby returning false . It really depends on how this method is used, and as a “serious” empty argument.
source share