public class SuffixPairChecker {
.1point3acres
// Trie Node class
static class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();.
boolean isEndOfWord = false;
}
. 1point 3acres // Trie class
static class Trie {
TrieNode root = new TrieNode();
-baidu 1point3acres
// Insert a word in reverse order . .и public void insert(String word) {. ----
TrieNode node = root;
for (int i = word.length() - 1; i >= 0; i--) {
char c = word.charAt(i);
node = node.children.computeIfAbsent(c, k -> new TrieNode());
}. 1point 3 acres
node.isEndOfWord = true;
}
// Search for a suffix in the trie
public boolean searchSuffix(String word) {
TrieNode node = root;
for (int i = word.length() - 1; i >= 0; i--) {. From 1point 3acres bbs
char c = word.charAt(i);
if (!node.children.containsKey(c)) {
return false;
}
node = node.children.get(c);.--
if (node.isEndOfWord) { . Waral dи, return true;
}
}. 1point3acres
return node.isEndOfWord;
}
}
public int pairCheck(String[] words) {
Trie trie = new Trie();
int count = 0;
// Insert all words into the trie in reversed order
for (String word : words) {
trie.insert(word);
}
// Check each word against the trie for suffix match
for (String word : words) {
// Remove the word from the trie to avoid counting itself. check 1point3acres for more.
if (trie.searchSuffix(word)) {
count++;
}. .и
}
return count;
}
public static void main(String[] args) {
SuffixPairChecker checker = new SuffixPairChecker();
String[] words = {"apple", "ple", "banana", "na", "an"};
int result = checker.pairCheck(words);
System.out.println("Number of valid suffix pairs: " + result); // Expected output. 1point 3acres
}
}