变位程序测试

Anagram Program Testing

本文关键字:测试 程序      更新时间:2023-10-16

我的变位程序在我的dev-cpp中工作得很好,但在任何在线测试中,任何测试变位都会抛出错误的答案。有人能帮帮我吗?

#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;
}

与其尝试重新发明轮子,不如在<algorithm>中有一个简洁的函数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;
}

如果需要区分大小写,只需删除二进制谓词。

你的算法有问题。想象一下下面的场景:

Input1: ab
Input2: cdefab

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

同样的问题,例如:

Input1: aaaaaa
Input2: a

或:

Input1: aaaab
Input2: bbbba

你可以修改你的算法:

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

你可以在这里找到更多关于这些算法的细节。