#include <stdio.h>
int one_way(const char *a, const char *b)
{
int misses = 0, ia = 0, ib = 0, missed_index = 0;
while (a[ia] || b[ib]) {
/* Characters at this position match? Keep going... */
if (a[ia] == b[ib]) {
if (a[ia]) ++ia;
if (b[ib]) ++ib;
/* Mismatched characters? */
} else {
/* Already missed once; backtrack if skipped earlier, or bail. */
if (++misses > 1) {
if (missed_index) {
ia = missed_index;
ib = missed_index;
missed_index = 0;
}
else return 0;
/* No misses yet... */
} else {
/* Skip buffer A ahead if its next char matches buffer B. */
if (a[ia] && a[ia + 1] == b[ib]) {
++ia;
missed_index = ia;
/* Skip buffer B ahead if its next char matches buffer A. */
}
if (b[ib] && b[ib + 1] == a[ia]) {
++ib;
missed_index = ib;
/* Skip both buffers ahead, if neither was skipped. */
}
if (!missed_index) {
if (a[ia]) ++ia;
if (b[ib]) ++ib;
}
}
}
}
return 1;
}
int test(const char *a, const char *b, int expected)
{
int r = one_way(a, b);
printf("%s\t%s\t%d\t", a, b, r);
if (r == expected) printf("(ok)\n");
else printf("(FAIL)\n");
}
int main()
{
test("same", "same", 1);
test("pale", "ple", 1);
test("ple", "pale", 1);
test("pales", "pale", 1);
test("palest", "pale", 0);
test("pale", "bale", 1);
test("pale", "bake", 0);
test("aa", "ba", 1);
test("xy", "zx", 0);
test("xyy", "yxx", 0);
test("xyw", "zxy", 0);
test("xxyx", "yxxy", 0);
test("xyyx", "yyxx", 0);
test("xyzz", "xzyy", 0);
return 0;
}