import java.util.HashSet;
import java.util.Set;
public class CommonWords {
/**
Normalize a string:
- Convert to lowercase
- Replace any non-letter with a space
This ensures consistent word comparison.
*/
private static String normalize(String s) {
StringBuilder sb = new StringBuilder(s.length());
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
sb.append(Character.toLowerCase(c));
} else {
sb.append(' ');
}
}
return sb.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
*/
private static Set<String> extractWords(String s) {
String normalized = normalize(s);
String[] parts = normalized.split("\\s+");
Set<String> words = new HashSet<>();
for (String w : parts) {
if (!w.isEmpty()) {
words.add(w);
}
}
return words;
}
/**
Find common words between two strings.
This function:
- Extracts words from both strings
- Uses set intersection for efficiency
- Returns a new Set<String> containing the common words
*/
private static Set<String> findCommonWords(String a, String b) {
Set<String> wordsA = extractWords(a);
Set<String> wordsB = extractWords(b);
Set<String> common = new HashSet<>(wordsA);
common.retainAll(wordsB); // efficient set intersection
return common;
}
public static void main(String[] args) {
String s1 = "The quick brown fox jumps over the lazy dog.";
String s2 = "A lazy dog sleeps while the quick fox runs away.";
Set<String> common = findCommonWords(s1, s2);
System.out.println("Common words:");
for (String w : common) {
System.out.println(w);
}
}
}
/*
run:
Common words:
the
quick
lazy
dog
fox
*/