给定字符串arr []和Q查询的数组,其中每个查询均由字符串str组成,任务是在数组中找到与给定字符串str的前缀匹配的最长字符串,即该字符串必须为str的前缀。
例子:
Input: arr[] = {“GeeksForGeeks”, “GeeksForGeeksd”, “Arnab”, “Art”},
q[] = {“GeeksForGeeks”, “Ar”, “Art”}
Output:
GeeksForGeeks
-1
Art
Input: arr[] = {“Geek”, “Geek”, “Geekss”, “Geekk”},
q[] = {“Geek”, “Geeks”, “Geekk”, “Gee”}
Output:
Geek
-1
Geekk
-1
原始的方法:对于通过阵列并检查其与给定的字符串的前缀,存储和打印中最长的字符串相匹配的字符串的每个给定的字符串遍历。
高效的方法:可以使用Trie解决此问题。我们将形成一个线索并插入阵列的字符串线索,发现完全给定字符串的前缀匹配的最长的字符串。
下面是上述方法的实现:
// C++ implementation of the approach
#include
using namespace std;
const int ALPHABET_SIZE = 26;
// Trie node
struct TrieNode {
struct TrieNode* children[ALPHABET_SIZE];
// isEndOfWord is true if the node represents
// end of a word
bool isEndOfWord;
};
// Returns new trie node (initialized to NULLs)
struct TrieNode* getNode(void)
{
struct TrieNode* pNode = new TrieNode;
pNode->isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
return pNode;
}
// If not present, inserts key into trie
// If the key is prefix of trie node, just
// marks leaf node
void insert(struct TrieNode* root, string key)
{
struct TrieNode* pCrawl = root;
for (int i = 0; i < key.length(); i++) {
int index = key[i] - 'a';
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
if (i == key.length() - 1)
// Mark last node as leaf
pCrawl->children[index]->isEndOfWord = true;
pCrawl = pCrawl->children[index];
}
}
string getString(char x)
{
// string class has a constructor
// that allows us to specify size of
// string as first parameter and character
// to be filled in given size as second
// parameter.
string s(1, x);
return s;
}
// Function to return the
// longest required string
string search(struct TrieNode* root, string key)
{
struct TrieNode* pCrawl = root;
// Prefix of the string
string s = "";
for (int i = 0; i < key.length(); i++) {
int index = key[i] - 'a';
if (!pCrawl->children[index])
break;
s += getString((char)key[i]);
pCrawl = pCrawl->children[index];
}
if (pCrawl->isEndOfWord)
return s;
return "-1";
}
// Driver code
int main()
{
string arr[] = { "Geeks", "Geek",
"Geekss", "Geekks" };
int n = sizeof(arr) / sizeof(string);
// Construct trie
struct TrieNode* root = getNode();
for (int i = 0; i < n; i++)
insert(root, arr[i]);
string queries[] = { "Geek", "Geeks", "Geekk", "Gee" };
int q = sizeof(queries) / sizeof(string);
for (int i = 0; i < q; i++)
cout << search(root, queries[i]) << endl;
return 0;
}
输出:
Geek
Geeks
-1
-1