【问题标题】:Anagram Program Testing字谜程序测试
【发布时间】:2016-01-12 06:09:23
【问题描述】:

我的 anagram 程序在我的 dev-cpp 中运行良好,但在任何在线测试人员中,任何测试 anagram 都会抛出错误的答案。有人可以帮我吗?

#include<iostream>
#include<cstring>
using namespace std;

int main()
{

    char input1[10000];
    char input2[10000];
    cin >> input1;
    getchar();
    cin >> input2;
    getchar();

    int leng;
    leng = strlen(input1);
    bool output[leng];

    for(int i=0; i<leng; i++){
            for(int y=0; y<leng; y++){
                    if( input1[i] == input2[y] ){
                        output[i] = true;
                    }
            }
    }

    for(int o=0; o<leng; o++ ){
        if( (o+1) == leng){
            if( output[o] == true){
                 cout << "ano" << endl;
                 break;
            }
        }else if(output[o] == true) {
                 continue;
        }
        cout << "nie" << endl;
        break;
    }


    getchar();
    return 0;
}

【问题讨论】:

  • 你能在你的问题中展示一个对你有用但不能在线的例子吗?
  • 可能... kalerab mrkvicka ...在 pc 中它抛出“不”,但在线“是”,但我不确定那个例子

标签: c++ anagram


【解决方案1】:

与其试图重新发明轮子,&lt;algorithm&gt; 中有一个简洁的函数is_permutation 可以使这个问题变得微不足道。 .

#include <algorithm>

bool isAnagram(std::string a, std::string b) {
    if(a.size() == b.size()) {
        return std::is_permutation ( a.begin(), a.end(), b.begin(), [](char x, char y){return std::tolower(x) == std::tolower(y);} );
    }
    return false;
}

如果您想要区分大小写,只需删除二进制预测。 Try it here

【讨论】:

  • 你说的很对,但我认为 OP 正在尝试实现他自己的算法来学习编程......这只是我的一个想法。
  • 是的,我只是学习,但谢谢大家。我知道哪里出错了。
【解决方案2】:

您的算法有问题。想象以下场景:

Input1: ab
Input2: cdefab

您的算法将返回 OK,因为它只会检查 input1 的 a 和 b 字符是否存在于 input2 中。

与示例相同的问题,例如:

Input1: aaaaaa
Input2: a

或者:

Input1: aaaab
Input2: bbbba

您可以通过以下方式更改算法:

  • 使用 256(ASCII 字符索引)数组计算字符int 初始化为 0。input1 递增,input2 递减,最后你的数组应该用 0 填充。O(n) 算法
  • 对您的两个输入进行排序并逐个字符地比较它们。 O(n^2) 算法

您可以找到有关这些算法的更多详细信息here

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2012-10-11
    • 2020-07-09
    • 1970-01-01
    • 2014-06-12
    相关资源
    最近更新 更多