c++ - 更改字符串中的一个字母以生成新单词 c++
问题描述
在字典中查找与任何给定的四字母输入仅相差一个字母的单词集。例如,单词“desk”可以将第二个字母替换为“i”并得到“disk”。
这就是我到目前为止所拥有的。我被困在如何开始这个过程,非常感谢任何帮助。
int main (int argc, char ** argv) {
string word;
int count; // count total # of words after each query
ifstream inFile;
inFile.open(argv[1]);
while (cin) {
cout << "Please input a 4 letter word:";
cin >> word;
if (word.size() == 4) {
transform(word.begin(), word.end(), word.begin(), _tolower);
count++;
cout << word << endl;
cout << "Total " << count << " words." << endl;
} else {
cout << "wrong length!" << endl;
}
}
}
样本输出
请输入4个字母的单词:win
长度错误!酒
aine bine cine dine eine fine gine hine kine line mine 九 pine rine sine tine vine wane wene wicewide 妻子 wile wime wina 风翼 wini wink winn wint wint winy wine wine wite wive wone wyne 共 41 个字。
解决方案
用于此的一个很好的算法是std::inner_product
. 假设您有 2 个字符串word
和test
,它们的长度相同,您可以总结它们之间成对不同的字符数:
int res = std::inner_product(word.begin(), word.end(),
test.begin(),
0,
std::plus{},
std::not_equal_to{});
如果此结果小于2
,则test
和word
字符串最多有一个字符不同:
if (res < 2)
{
// ... successful match
}
您可能应该将其包装在一个接受 2 个字符串并返回 a 的函数中bool
,因此您可以为要测试的集合中的所有单词调用此函数。
推荐阅读
- excel - 使用更改单元格引用在 VBA 中创建和粘贴公式
- promise - 从 axios 的响应头中获取数据
- python - 否则小程序不生效
- reactjs - TypeError:无法读取未定义的属性“txdate”
- python - selenium:TypeError:“FirefoxWebElement”对象不可下标
- python - 使用 for 在 python 中创建多个 Rx 主题
- javascript - 什么是更高性能的结构指令或在 Angular 模板的表达式中使用函数?
- r - 在 R 中抓取动态网页
- html - 当用户以 Angular 7 反应形式输入货币值时,如何自动插入逗号,没有 [(ngModel)]
- python - 如何对矩阵列中的值进行排序?