The following is code for comparing a String A and String B with atmost one mismatch
i.e.,
ABC is same as ABX or AXC or XBC but, not same as AXZ
I did check several cases but, the website says it provides wrong answer. Could someone help to figure out where does this code fail?
Also, I’d be glad if someone could provide a better algorithm for the same problem.
TY
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;
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;
}
One problem is that if
b.length()is even, then you comparea[pos + b.length() / 2]tob[b.length() / 2]twice: once wheni == mid - 1, and once wheni == mid. So something likecompare("abcd", 0, "abbd")returns0, because it counts the'c'-vs.-'b'discrepancy as two separate mismatches.I recommend that you simply strip out all logic related to
mid. It serves no purpose other than massively complicating your code. If you iterate straight from0tob.length() - 1, you’ll be much better off.