c++ - 使用similarity() 函数查找相似的字符串
问题描述
假设一个函数similarity()
接受两个字符串作为参数。如果两个字符串相似,则返回接近 1 的数字,否则返回接近 0 的数字。
到目前为止,我有一个二叉树,其中每个节点都包含一个字符串作为数据。我想创建一个函数,它将逐个节点浏览该树节点并返回具有最高相似性的单词。
试图:
使用@AshutoshRaghuwanshi 的答案,我得到了
void Tree::traverse(Node* rootNode, float& score, std::string& bestMatch, std::string& word)
{
if(rootNode == nullptr) return;
if(similarity(rootNode->data, word)>score){
score = similarity(rootNode->data, word);
bestMatch = rootNode->data;
}
traverse(rootNode->left, score, bestMatch, word);
traverse(rootNode->right, score, bestMatch, word);
}
std::string Tree::browseTree(const std::string& word) const{
if(isEmpty()){
throw std::invalid_argument("The tree is empty!");
}
Node * currentNode = root;
float score=0;
std::string bestMatch;
traverse(currentNode->left, score, bestMatch, word);
traverse(currentNode->right, score, bestMatch, word);
if(score>.90){
return bestMatch;
}else{
throw std::invalid_argument("Word not found");
}
}
好像没那么好用?我哪里错了?
解决方案
void Tree::traverse(Node* rootNode, float& score, std::string& bestMatch, std::string& word)
{
if(rootNode == nullptr) return;
float s = similarity(rootNode->data, word);
if(s>score){
score = s;
bestMatch = rootNode->data;
}
traverse(rootNode->left, score, bestMatch, word);
traverse(rootNode->right, score, bestMatch, word);
}
std::string Tree::browseTree(const std::string& word) const{
if(isEmpty()){
throw std::invalid_argument("The tree is empty!");
}
Node * currentNode = root; //replace this line
float score=0;
std::string bestMatch;
traverse(root, score, bestMatch, word);
if(score>.90){
return bestMatch;
}else{
throw std::invalid_argument("Word not found");
}
}
这段代码很可能会起作用。请将注释中指示的行替换为二叉树的实际根节点。
推荐阅读
- r - 更改函数绘图的粒度以使绘图看起来平滑
- python-3.7 - Platypus NSGA-II 如果在 unique_ids 中没有 id 则会给出错误:TypeError: unhashable type: 'numpy.ndarray'
- python - 我们如何计算数据中客户的不稳定(相似或不同的行为)?
- excel - VBA 代码执行时间问题...为什么添加 Dim 语句会加快对空白 Sub 的调用?
- angular - 使用 ngx-translate 本地化 Angular 库
- knitr - 如何从 knitr 隐藏此消息输出?
- windows-10 - 为什么我尝试将“make”添加到路径中不允许我使用 make
- audio - 我需要一种捕获来自(游戏、网站、音乐播放器)的内部桌面音频的方法
- python - 每次按 Enter 时如何从用户那里获取数据并将这些数据传递给函数?
- shell - 为什么 zsh `for` 循环错误并带有 `command not found: filename.txt`?尽管 filename.txt 是参数而不是命令