714218. Prefix Suffix String
Medium
Prefix Suffix String
Summary
Given a string S and an integer K, find all substrings in S that have exactly K as their prefix and suffix. The problem involves strings, Trie data structure, and algorithmic thinking.
Detailed Explanation
The approach to this problem is to construct a Trie using the characters of the input string. Then, traverse the Trie and for each node at level K, check if it has more than one child node (which means there's a suffix of length K present). If yes, then all substrings with prefix and suffix as the current character can be obtained by traversing down from that node.
Here is the step-by-step breakdown:
- Construct a Trie using the characters of the input string.
- Traverse the Trie and for each node at level
K, check if it has more than one child node (which means there's a suffix of lengthKpresent). - If yes, then all substrings with prefix and suffix as the current character can be obtained by traversing down from that node.
- For each node found in step 2, perform DFS to get all possible substrings.
Time complexity is O(N) where N is the length of the input string. Space complexity is also O(N) due to the Trie structure used.
Optimized Solutions
Java
class Solution {
public List<String> prefixSuffix(String S, int K) {
TrieNode root = new TrieNode();
for (char c : S.toCharArray()) {
TrieNode node = root;
for (int i = 0; i < K; i++) {
if (!node.children.containsKey(c)) {
node.children.put(c, new TrieNode());
}
node = node.children.get(c);
}
node.isLeaf = true;
}
List<String> result = new ArrayList<>();
for (Map.Entry<Character, TrieNode> entry : root.children.entrySet()) {
if (entry.getValue().isLeaf) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < K; i++) {
sb.append(entry.getKey());
}
result.add(sb.toString());
}
}
return result;
}
}
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean isLeaf;
}