a,b & c will each increment twice, at which point
s1[a]=’f', s1[b]=’e', and s3[c] = ‘a’.
I think your handler won’t do anything in that case (both ifs return false), and i don’t see what it could do. Cool idea :) though i suspect backtracking is unavoidable
]]>s3 is a reshuffle of s1 and s2.
but your algorithm will return false, because with the first char (‘a’) you increment s1′s index instead of s2, and in the next iteration you have -
s1[i]=’b’
s2[i]=’a’
s3[i]=’e’
In such a case you’d need to backtrack
]]>
def isCorrectShuffle(str1,str2,str3):
iter1,iter2,iter3 = (0,0,0)
for iter3 in xrange(len(str3)):
if iter1 < len(str1) and iter2 < len(str2) and
str3[iter3] == str1[iter1] and str3[iter3] == str2[iter2]:
return isCorrectShuffle(str1[iter1+1:],str2[iter2:],str3[iter3+1:])
or
isCorrectShuffle(str1[iter1:],str2[iter2+1:],str3[iter3+1:])
if iter1 < len(str1) and str3[iter3] == str1[iter1]:
iter1 += 1
elif iter2 < len(str2) and str3[iter3] == str2[iter2]:
iter2 += 1
else:
return False;
return (iter1 == len(str1)) and (iter2 == len(str2))
public boolean isCorrectlyShuffled(String str1, String str2,String shuffledStr) {
//handle null strings by converting them to empty strings
str1 = (str1 == null) ? “” : str1;
str2 = (str2 == null) ? “” : str2;
shuffledStr = (shuffledStr == null) ? “” : shuffledStr;
//eliminate some cases by checking string lengths
//and empty-nonempty str1-str2 inputs
if ((str1.length() + str2.length() != shuffledStr.length())
|| ((str1.isEmpty() || str2.isEmpty()) && !(str1 + str2).equals(shuffledStr)))
return false;
//use two index values for two strings
int ind1 = 0;
int ind2 = 0;
//keep a hashmap for the case of (str1[i] == str2[i] == shuffledStr[i])
Map charBackup = new HashMap();
for (int i = 0; i < shuffledStr.length(); i++) {
//count occurences of a char at current indexes of three strings
int occurence = 0;
char currChar = shuffledStr.charAt(i);
if (ind1 < str1.length() && currChar == str1.charAt(ind1)) {
ind1++;
occurence++;
}
if (ind2 0) {
occurence++;
charBackup.put(currChar, –backupLimit);
}
//if a char occured more than once, add the char to the hashmap
//to be used later as a backup
if (occurence == 2) charBackup.put(currChar, backupLimit + 1);
else if (occurence == 0) return false;
}
return true;
}