Compare Strings With One Error
January 29, 2016
I don’t know if today’s exercise comes from an interview question or from somebody’s homework, but it’s a good exercise:
Given two strings, determine if they are the same except for exactly one difference. Two identical strings fail to match. Two strings that differ in two or more characters fail to match. Two strings with lengths that differ by one match if and only if they are identical except for one additional character. Indicate the index where the difference occurs, or report failure if the two input strings do not differ in exactly one character.
Your task is to write a program that compares strings with one error. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Common Lisp, we can use MISMATCH to find where two sequences differ.
However, we have several cases to consider:
same length:
“abcde”
“abxde”
different lengths:
“abc”
“ab”
“abcde”
“abde”
“abc”
“bc”
Python version
#include
#include
#include
#include
using namespace std;
//Function incorporating Solution.
void Solution(void);
void main(void)
{
Solution();
}
void Solution(void)
{
int DiffCount = 0;
int LenA, LenB;
string A,B;
cin>>A>>B;
LenA = A.length(), LenB = B.length();
if ((LenA == LenB))
{
for (int X = 0; X = 0 && DiffCount!= 1) cout << "Error";
else cout << "No Error";
}
else if (abs(LenA – LenB) == 1)
{
for (int X = 0; X 0) cout << "Error";
else cout << "No Error";
}
else cout << "Error";
}
Python solution. Basic idea is to find where the strings don’t match. Then there are two cases:
1) s and t are the same length, so the mismatch must be a character substitution and the rest of the strings must match after skipping the mismatch (s[i+1:] == t[i+1:]); and
2) s is shorter than t, so the rest of s must match the rest of t after skipping a character (s[i:] == t[i+1:])