首页 > 解决方案 > 更改字符串中的一个字母以生成新单词 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 wy​​ne 共 41 个字。

标签: c++stl

解决方案


用于此的一个很好的算法是std::inner_product. 假设您有 2 个字符串wordtest,它们的长度相同,您可以总结它们之间成对不同的字符数:

int res = std::inner_product(word.begin(), word.end(), 
                             test.begin(), 
                             0,
                             std::plus{}, 
                             std::not_equal_to{});

如果此结果小于2,则testword字符串最多有一个字符不同:

if (res < 2)
{
  // ... successful match
}

您可能应该将其包装在一个接受 2 个字符串并返回 a 的函数中bool,因此您可以为要测试的集合中的所有单词调用此函数。


推荐阅读