变位程序测试
Anagram Program Testing
我的变位程序在我的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)藻类
你可以在这里找到更多关于这些算法的细节。
相关文章:
- 如何将参数传递给Google基准测试程序
- Cmake无法在qt-creater/collect2上编译简单的测试程序:错误:ld
- CMake 和 Visual Studio 2015 - C 编译器 cl.exe 无法编译简单的测试程序
- C++编译器 g++.exe 无法编译简单的测试程序 - 确定 CXX 编译器是否工作失败
- 如何编译和运行 vmmlib 测试程序?
- C++测试程序中的非法系统调用(对角矩阵元素程序的总和)
- 在我的测试程序中,为什么 cv::resize 不能执行,而 cvtColor 可以?
- 使用 QtCreator 构建 CUDA/C++ 测试程序时出现错误 2
- SDL 测试程序 - "No such file or directory"
- 软件定义无线电 USRP X310 的测试程序
- CMake 在尝试编译简单测试程序时失败
- 无法运行简单的 std::async 和 std::future 测试程序。错误:"has initializer but incomplete type."发生了什么?
- C 编译器无法编译简单的测试程序
- 从测试程序访问共享库中具有静态私有字段的类
- CL.EXE无法编译简单的测试程序VS2017
- 由于某种原因,FSTREAM测试程序崩溃
- Windows CMake 不会编译测试程序
- 为什么在我的测试程序中,从字符缓冲区读取一个int时,"std::copy"5x(!)比"
- 在Windows 7(Mingw,Code :: Blocks)下进行编译,以获取Botan Library测试程序
- 在本地机器上进行应力测试C++程序