object CommonWordsApp {
/*
Normalize a string:
- Convert letters to lowercase
- Replace any non-letter with a space
This ensures consistent word comparison.
*/
def normalize(text: String): String = {
val builder = new StringBuilder(text.length)
for (ch <- text) {
if (ch.isLetter)
builder.append(ch.toLower)
else
builder.append(' ')
}
builder.toString
}
/*
Extract words from a string.
This function:
- Normalizes the input
- Splits on whitespace
- Filters out empty entries
- Returns a Set[String] for fast lookup and automatic duplicate removal
*/
def extractWords(text: String): Set[String] = {
val normalized = normalize(text)
normalized.split("\\s+").filter(_.nonEmpty).toSet
}
/*
Find common words between two strings.
This function:
- Extracts words from both strings
- Uses set intersection for efficiency
- Returns a Set[String] containing the common words
*/
def findCommonWords(a: String, b: String): Set[String] = {
val wordsA = extractWords(a)
val wordsB = extractWords(b)
wordsA intersect wordsB
}
def main(args: Array[String]): Unit = {
val s1 = "The quick brown fox jumps over the lazy dog."
val s2 = "A lazy dog sleeps while the quick fox runs away."
val common = findCommonWords(s1, s2)
println("Common words:")
common.foreach(println)
}
}
/*
run:
Common words:
lazy
dog
quick
fox
the
*/