📌  相关文章
📜  在阵列中,其与给定的字符串的前缀匹配最长的字符串

📅  最后修改于: 2021-04-17 10:13:40             🧑  作者: Mango

给定字符串arr []Q查询的数组,其中每个查询均由字符串str组成,任务是在数组中找到与给定字符串str的前缀匹配的最长字符串,即该字符串必须为str的前缀。

例子:

原始的方法:对于通过阵列并检查其与给定的字符串的前缀,存储和打印中最长的字符串相匹配的字符串的每个给定的字符串遍历。

高效的方法:可以使用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