longestCommonSubsequenceLengthOf function

int longestCommonSubsequenceLengthOf(
  1. String source,
  2. String target, {
  3. bool ignoreCase = false,
  4. bool ignoreWhitespace = false,
  5. bool ignoreNumbers = false,
  6. bool alphaNumericOnly = false,
})

Returns the length of the longest common subsequence of two strings.

Parameters

  • source and target are two strings.
  • if ignoreCase is true, the character case shall be ignored.
  • if ignoreWhitespace is true, space, tab, newlines etc whitespace characters will be ignored.
  • if ignoreNumbers is true, numbers will be ignored.
  • if alphaNumericOnly is true, only letters and digits will be matched.

TIPS: You can pass both ignoreNumbers and alphaNumericOnly to true to ignore everything else except letters.

Details

Common subsequence between two strings is a set of characters appearing in both in the same order. Unlike substrings, the subsequences are not required occupy consecutive positions.

This functions returns the length of the longest common subsequence between source and target without modifying their contents.

This is similar to Levenshtein distance, where only insertion and deletion operations are permitted, and substitution is not.


If n is the length of source and m is the length of target,
Complexity: Time O(nm) | Space O(n)

Implementation

int longestCommonSubsequenceLengthOf(
  String source,
  String target, {
  bool ignoreCase = false,
  bool ignoreWhitespace = false,
  bool ignoreNumbers = false,
  bool alphaNumericOnly = false,
}) {
  source = cleanupString(
    source,
    ignoreCase: ignoreCase,
    ignoreWhitespace: ignoreWhitespace,
    ignoreNumbers: ignoreNumbers,
    alphaNumericOnly: alphaNumericOnly,
  );
  target = cleanupString(
    target,
    ignoreCase: ignoreCase,
    ignoreWhitespace: ignoreWhitespace,
    ignoreNumbers: ignoreNumbers,
    alphaNumericOnly: alphaNumericOnly,
  );
  return longestCommonSubsequenceLength(source.codeUnits, target.codeUnits);
}