Dusan Punosevac
BAN USER- 2of 2 votes
AnswersWe have two strings A and B with the same super set of characters. We need to change these strings to obtain two equal strings. In each move we can perform one of the following operations:
- Dusan Punosevac
1- swap two consecutive characters of a string
2- swap the first and the last characters of a string
A move can be performed on either string.
What is the minimum number of moves that we need in order to obtain two equal strings?
Input Format and Constraints:
The first and the second line of the input contains two strings A and B. It is guaranteed that the superset their characters are equal.
1 <= length(A) = length(B) <= 2000
All the input characters are between 'a' and 'z'
Output Format:
Print the minimum number of moves to the only line of the output
Sample input:
aab
baa
Sample output:
1
Explanation:
Swap the first and last character of the string aab to convert it to baa. The two strings are now equal.| Report Duplicate | Flag | PURGE
char[] aChar = a.toCharArray();
char[] bChar = b.toCharArray();
char cChar;
if ((a.length() >= 1 && a.length() <= 2000) && a.length() == b.length()) {
if (aChar != bChar) {
for (int i = 0; i < aChar.length; i++) {
for (int j = i + 1; j < aChar.length; j++) {
if (aChar[i] != bChar[i]) {
if (aChar[j] == bChar[i] && j < aChar.length) {
cChar = aChar[j];
aChar[j] = aChar[i];
aChar[i] = cChar;
moves++;
} else if (aChar[aChar.length - 1] == bChar[i]) {
cChar = aChar[aChar.length - 1];
aChar[aChar.length - 1] = aChar[i];
aChar[i] = cChar;
moves++;
} else {
if (aChar[j] != aChar[i] && j < aChar.length) {
if (aChar[j] == bChar[j]) {
cChar = bChar[j];
bChar[j] = bChar[i];
bChar[i] = cChar;
moves++;
}
cChar = aChar[j];
aChar[j] = aChar[i];
aChar[i] = cChar;
moves++;
} else if (bChar[j] != bChar[i]
&& i + 1 < aChar.length) {
if (aChar[j] == bChar[j]
&& aChar[j] != aChar[i]) {
cChar = aChar[j];
aChar[j] = aChar[i];
aChar[i] = cChar;
moves++;
}
cChar = bChar[j];
bChar[j] = bChar[i];
bChar[i] = cChar;
moves++;
}
}
if (aChar == bChar) {
break;
}
}
}
}
}
System.out.println("Minimum number of moves: " + moves);
}
But i think it's still not good.
Well yes, but it gave me idea. I did it similar, and this input gives me output 4.
- Dusan Punosevac September 22, 2014Thank you ravio. It is quite easy. Just make 2 loops and that j=i+1 and check. Well I guess I didn't sort the whole problem in my head. Shame on me. :)
- Dusan Punosevac September 22, 2014
So i did it. Sorry for taking this log to post it, but here it is:
- Dusan Punosevac October 13, 2014