以下是几种用C++实现的方式,通过字符串前缀从数组中找出搜索建议列表:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 方法一:线性搜索
vector<string> searchSuggestions1(const vector<string>& arr, const string& prefix) {
vector<string> suggestions;
for (const auto& word : arr) {
if (word.substr(0, prefix.size()) == prefix) {
suggestions.push_back(word);
}
}
return suggestions;
}
// 方法二:二分搜索
vector<string> searchSuggestions2(const vector<string>& arr, const string& prefix) {
vector<string> suggestions;
auto lower = lower_bound(arr.begin(), arr.end(), prefix);
for (auto it = lower; it != arr.end(); ++it) {
if ((*it).substr(0, prefix.size()) != prefix) break;
suggestions.push_back(*it);
}
return suggestions;
}
// 方法三:Trie树(字典树)
class TrieNode {
public:
vector<TrieNode*> children;
};
void insertWord(TrieNode* root, const string& word) {
TrieNode* node = root;
for (char ch : word) {
int index = ch - 'a';
if (!node->children[index]) {
node->children[index] = new TrieNode();
}
node = node->children[index];
}
}
void findWords(TrieNode* node, string& currentPrefix, vector<string>& result, const string& prefix) {
if (result.size() == 3 || !node)
return;
if (!currentPrefix.empty() && currentPrefix.find(prefix) == 0)
result.push_back(currentPrefix);
for (int i = 0; i < 26; ++i) {
if (node->children[i]) {
currentPrefix.push_back('a' + i);
findWords(node->children[i], currentPrefix, result, prefix);
currentPrefix.pop_back();
}
}
}
vector<string> searchSuggestions3(const vector<string>& arr, const string& prefix) {
TrieNode* root = new TrieNode();
for (const auto& word : arr)
insertWord(root, word);
vector<string> suggestions;
string currentPrefix;
findWords(root, currentPrefix, suggestions, prefix);
return suggestions;
}
int main() {
vector<string> arr = { "apple", "banana", "orange", "pear", "pineapple" };
string prefix = "app";
// 方法一:线性搜索
vector<string> suggestions1 = searchSuggestions1(arr, prefix);
// 方法二:二分搜索
sort(arr.begin(), arr.end());
vector<string> suggestions2 = searchSuggestions2(arr, prefix);
// 方法三:Trie树
vector<string> suggestions3 = searchSuggestions3(arr, prefix);
cout << "方法一(线性搜索)的结果:" << endl;
for (const auto& suggestion : suggestions1) {
cout << suggestion << endl;
}
cout << "\n方法二(二分搜索)的结果:" << endl;
for (const auto& suggestion : suggestions2) {
cout << suggestion << endl;
}
cout << "\n方法三(Trie树)的结果:" << endl;
for (const auto& suggestion : suggestions3) {
cout << suggestion << endl;
}
return 0;
}
以上代码展示了三种常见的实现方式:
方法一:线性搜索。遍历数组,逐个比较字符串的前缀,将符合条件的字符串添加到结果列表中。
方法二:二分搜索。对数组进行排序,然后使用二分搜索找到第一个以指定前缀开头的字符串位置,再往后遍历直至不满足前缀要求。
方法三:Trie树(字典树)。构建一个Trie树,用于高效地存储和查找字符串。先插入所有字符串,然后通过递归查找匹配前缀的所有单词。
您可以选择其中一种方法或多种方法来实现,根据具体情况和需求选择最适合的方式。
内容由零声教学AI助手提供,问题来源于学员提问