简体   繁体   中英

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[]. You may assume that 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. Capital letters occupy the range 65-90 (*), see for example this page . So pat actually looks like this: {65, 66, 67, 68} .

You're trying to input into hashpat using these numbers, which are far bigger than the length of the array. You need to allocate these to be of size 256, which conveniently you already have as a define.

int hashpat[MAX]={0};
int hashtxt[MAX]={0};

Some other random advice:

  • Given that you're passing in char* , you should probably make these char arrays.
  • Both the arguments of search and the variables in main should be const char* , since that's the type of the string literals
  • Given you're using C++, you should look into using vector and string instead of arrays and chars, which will generally makes things a bit easier.

(*) Assuming we're in the ASCII/UTF-8, but that's a whole other kettle of fish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM