findClosestWord function

String findClosestWord(
  1. Set<String> dictionary,
  2. String word
)

Finds the closest matching word in a dictionary for a given input word.

This function takes a set of dictionary words and an input word, and returns the closest matching word from the dictionary based on the Levenshtein distance. It examines all words in the dictionary and returns the one with the minimum Levenshtein distance. If multiple words have the same minimum distance, it returns the longest one among them.

Implementation

String findClosestWord(final Set<String> dictionary, final String word) {
  String closestMatch = dictionary.first; // Start with any word from dictionary
  int minDistance = levenshteinDistance(word, closestMatch.toLowerCase());

  for (String dictWord in dictionary) {
    int distance = levenshteinDistance(word, dictWord.toLowerCase());
    if (distance < minDistance ||
        (distance == minDistance && dictWord.length > closestMatch.length)) {
      minDistance = distance;
      closestMatch = dictWord;
    }
  }

  return closestMatch;
}