Anagram程序测试

时间:2015-10-14 08:39:20

标签: c++ anagram

我的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;
}

2 个答案:

答案 0 :(得分:1)

而不是试图重新发明轮子,is_permutation中有一个简洁的函数<algorithm>可以使这个问题变得微不足道。 。

#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

答案 1 :(得分:0)

您的算法存在问题。想象一下以下场景:

Input1: ab
Input2: cdefab

您的算法将返回OK,因为它只会检查&amp; b input1的字符存在于input2中。

与例如:

相同的问题
Input1: aaaaaa
Input2: a

或者:

Input1: aaaab
Input2: bbbba

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

  • 使用256(ASCII中的字符索引)int初始化为0来计算字符数。输入1的递增和input2的递减,最后您的数组应填充0. O(n) ALGO
  • 对两个输入进行排序,并在字符后比较它们。 O(n ^ 2)algo

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