/*
Normalize a string:
- Convert letters to lowercase
- Replace any non-letter with a space
This ensures consistent word comparison.
*/
fun normalize(text: String): String {
val builder = StringBuilder(text.length)
for (ch in text) {
if (ch.isLetter()) {
builder.append(ch.lowercaseChar())
} else {
builder.append(' ')
}
}
return 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
*/
fun extractWords(text: String): Set<String> {
val normalized: String = normalize(text)
return normalized
.split(Regex("\\s+"))
.filter { it.isNotEmpty() }
.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
*/
fun findCommonWords(a: String, b: String): Set<String> {
val wordsA: Set<String> = extractWords(a)
val wordsB: Set<String> = extractWords(b)
return wordsA intersect wordsB
}
/*
Main execution
*/
fun main() {
val s1: String = "The quick brown fox jumps over the lazy dog."
val s2: String = "A lazy dog sleeps while the quick fox runs away."
val common: Set<String> = findCommonWords(s1, s2)
println("Common words:")
for (w in common) {
println(w)
}
}
/*
run:
Common words:
the
quick
fox
lazy
dog
*/