I have two strings, both the same length. And I've to check if them can be expressed as XYZ and XZY, where Y and Z are not empty.
My solution is to 'eat' the same first letters of both strings and then find Longest Common Substring for rest. Then check if rest of first and rest of second string (without LCS) are equal. Problem is, that I heard of O(N) memory complexity algorithm for this, but all that I found is O(MN). I have limited memory, so it's important for me.
Second solution is to use "(.*)(.+)(.+)\1\3\2" regex, but this is very poor solution.
Anyone have other ideas?
Something like this perhaps:
If memory is a real big issue for you, you can avoid the substrings by comparing char by char. For instance:
could be replaced by
Likewise you can avoid the strings x1, x2, y1 and y2 by introducing two similar for-loops where you compare char-by-char instead.
The code will be more difficult to read and understand but it will use less memory.