【发布时间】:2017-04-03 00:23:37
【问题描述】:
此函数旨在获取拼写错误的单词并对其进行排列,根据单词列表检查每个完整排列,直到找到匹配项。
一旦找到匹配项,该函数将终止并立即返回匹配的单词,而不需要进一步排列。
在当前状态下,该函数可以工作,但它会继续排列并找到匹配项,直到所有排列完成。
函数 find () 可以被认为是一个黑盒,如果单词与 dcnV 向量中的单词匹配,则返回 true,否则返回 false。该功能运行正常。
dcnV :包含字典中单词列表的字符串向量。
pos : 递归算法使用的整数。
p [] : 解数组。
used [] : 跟踪当前使用了哪些索引的数组 排列。
word : 从调用函数传入这个函数的单词(来自文本文件)。
string permute ( vector <string> dcnV , int pos , int p [] ,
int used [] , string & word )
{
string tgt = word; //sets tgt to have the same size as word
unsigned int n = word.size (); //determines for loop range
unsigned int i = 0; //iterator
/* base case: when the end of the array is reached,
* map tgt to word using p array indexes
* search dictionary vector dcnV for matching word
* if found, return tgt
*/
if ( pos == n && p [0] == 0 && p [n - 1] == n - 1 )
{
for ( i = 0; i < n; i++ )
{
tgt [i] = word [p[i]];
}
if ( find ( dcnV , tgt ) )
{
cout << "\n Found matching word: " << tgt;
return tgt;
}
}
// recursive permutation algorithm. this is functioning correctly
for ( i = 0; i < n; i++ )
{
if ( used [i] == 0 )
{
p [pos] = i;
used [i] = 1;
permute ( dcnV , pos + 1 , p , used , word );
used [i] = 0;
}
}
// if end of fn is reached without match, return tgt with '*' appended in
// front
return "*" + word;
}
尝试的无效解决方案:
使用静态向量保存匹配的单词,然后只返回该向量的第一个元素。
找到一个单词时设置一个标志,并在函数的开头添加一个逻辑检查,如果设置了标志,则立即返回。
setjmp、longjmp、exit、break、异常不得使用。
【问题讨论】: