3

Could someone suggest a better approach for a string comparison among two strings with atmost one mismatch.

Example:

  • A: abcdefghabX
  • B: abc
  • Output: 1 9

The above outputs are the positions of substring matches of abc in "A"

I tried the basic approach with two for loops but, it seems to be taking N*N time. This is a big factor for large inputs and is taking huge amount of time.

My algorithm is as such but, it isn't a best one for huge amount of data

int compare(string a,  int pos, string b)
{
    int count = 0;
    int length = b.length()-1;
    int mid = b.length() /2;

    if(pos+length >= a.length())
        return 0;
    if((length+1)%2 != 0)   {
        for(int i=0,j=pos;i<=mid;i++,j++)   {       
            if(i == mid)    {
                if(a[j] != b[i])
                    count ++;
            }
            else    {
                if(a[j] != b[i])
                    count ++;
                if(a[pos+length - i] != b[length -i]) 
                    count ++;
            }
            if(count >= 2) return 0;
        }
    }
    else    {
        for(int i=0,j=pos;i<mid;i++,j++)    {       
            if(i == mid)    {
                if(a[j] != b[i])
                    count ++;
            }
            else    {
                if(a[j] != b[i])
                    count ++;
                if(a[pos+length - i] != b[length -i]) 
                    count ++;
            }
            if(count >= 2) return 0;
        }
    }
    return 1;
}

2 Answers 2

3

What you want is implemented in agrep, so have a look at the algorithms it uses.

Sign up to request clarification or add additional context in comments.

Comments

2

I think what you're after is the Boyer-Moore algorithm.

Specifically, the approximate version here.

1 Comment

Thanks Joel... That helped a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.