[英]can anyone please tell me what's wrong with my c++ code?
question: Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[].问题:给定文本 txt[0..n-1] 和模式 pat[0..m-1],编写一个函数 search(char pat[], char txt[]) 来打印所有出现的 pat[]以及它在 txt[] 中的排列(或字谜)。 You may assume that n > m.您可以假设 n > m。
#include<iostream>
#include<cstring>
#define MAX 256
using namespace std;
void search(char *pat, char *txt)
{
int M = strlen(pat), N = strlen(txt);
int i,count=0,start=0 ;
int hashpat[26]={0},hashtxt[26]={0};
for(i=0;i<M;i++)
{
hashpat[pat[i]]++;
}
for(i=0;i<N;i++)
{
hashtxt[txt[i]]++;
if(hashtxt[txt[i]]<=hashpat[txt[i]])
count++;
if(count==M)
{ cout<<"Found at index"<<i-M<<"\n";
hashtxt[txt[start]]--;
if(hashpat[txt[start]]!=0) count--;
start++;
}
}
}
/* Driver program to test above function */
int main()
{
char txt[] = "BACDGABCDA";
char pat[] = "ABCD";
search(pat, txt);
return 0;
}
You haven't described the actual problem you're having, and I'm not going to go through and check if you're code satisfies the problem.你还没有描述你遇到的实际问题,我不会去检查你的代码是否满足问题。 However, there is at least one obvious flaw.但是,至少有一个明显的缺陷。
A char
is a single byte, and can hold numbers between 0-255. char
是单个字节,可以容纳 0-255 之间的数字。 Capital letters occupy the range 65-90 (*), see for example this page .大写字母的范围为 65-90 (*),例如参见本页。 So pat
actually looks like this: {65, 66, 67, 68}
.所以pat
实际上看起来像这样: {65, 66, 67, 68}
。
You're trying to input into hashpat
using these numbers, which are far bigger than the length of the array.您正在尝试使用这些数字输入hashpat
,这些数字远大于数组的长度。 You need to allocate these to be of size 256, which conveniently you already have as a define.您需要将这些分配为 256 的大小,这很方便您已经定义了。
int hashpat[MAX]={0};
int hashtxt[MAX]={0};
Some other random advice:其他一些随机建议:
char*
, you should probably make these char
arrays.鉴于您正在传入char*
,您可能应该制作这些char
数组。search
and the variables in main
should be const char*
, since that's the type of the string literals search
的参数和main
的变量都应该是const char*
,因为这是字符串文字的类型vector
and string
instead of arrays and chars, which will generally makes things a bit easier.鉴于您使用的是 C++,您应该考虑使用vector
和string
而不是数组和字符,这通常会使事情变得更容易一些。(*) Assuming we're in the ASCII/UTF-8, but that's a whole other kettle of fish. (*) 假设我们在 ASCII/UTF-8 中,但那是另外一锅鱼。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.