import Foundation
/*
Normalize a string:
- Convert letters to lowercase
- Replace any non-letter with a space
This ensures consistent word comparison.
*/
func normalize(_ text: String) -> String {
var result = ""
for ch in text {
if ch.isLetter {
result.append(ch.lowercased())
} else {
result.append(" ")
}
}
return result
}
/*
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
*/
func extractWords(_ text: String) -> Set<String> {
let normalized = normalize(text)
let parts = normalized.split { $0.isWhitespace }
return Set(parts.map(String.init))
}
/*
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
*/
func findCommonWords(_ a: String, _ b: String) -> Set<String> {
let wordsA = extractWords(a)
let wordsB = extractWords(b)
return wordsA.intersection(wordsB)
}
/*
Main execution
*/
let s1 = "The quick brown fox jumps over the lazy dog."
let s2 = "A lazy dog sleeps while the quick fox runs away."
let common = findCommonWords(s1, s2)
print("Common words:")
for w in common {
print(w)
}
/*
run:
Common words:
dog
lazy
quick
fox
the
*/