algorithm - Finding minimum moves required for making 2 strings equal -
this question 1 of online coding challenge (which has completed).
need logic how approach.
problem statement:
have 2 strings , b same super set of characters. need change these strings obtain 2 equal strings. in each move can perform 1 of following operations:
1. swap 2 consecutive characters of string 2. swap first , last characters of string
a move can performed on either string.
minimum number of moves need in order obtain 2 equal strings?
input format , constraints:
first , second line of input contains 2 strings , b. guaranteed superset characters equal.
1 <= length(a) = length(b) <= 2000 input characters between 'a' , 'z'
output format:
print minimum number of moves line of output
sample input: aab baa sample output: 1
explanation:
swap first , last character of string aab convert baa. 2 strings equal.
edit : here first try, i'm getting wrong output. can guide me wrong in approach.
int minstringmoves(char* a, char* b) { int length, pos, i, j, moves=0; char *ptr; length = strlen(a); for(i=0;i<length;i++) { // find first occurrence of b[i] in ptr = strchr(a,b[i]); pos = ptr - a; // if last element, swap first if(i==0 && pos == length-1) { swap(&a[0], &a[length-1]); moves++; } // else swap current index till pos else { for(j=pos;j>i;j--) { swap(&a[j],&a[j-1]); moves++; } } // if equal, break if(strcmp(a,b) == 0) break; } return moves; }
take @ example:
aaaaaaaaab abaaaaaaaa
your solution: 8
aaaaaaaaab -> aaaaaaaaba -> aaaaaaabaa -> aaaaaabaaa -> aaaaabaaaa -> aaaabaaaaa -> aaabaaaaaa -> aabaaaaaaa -> abaaaaaaaa
proper solution: 2
aaaaaaaaab -> baaaaaaaaa -> abaaaaaaaa
you should check if swapping in other direction give better result.
but ruin previous part of string. eg:
caaaaaaaab cbaaaaaaaa caaaaaaaab -> baaaaaaaac -> abaaaaaaac
you need swap here put 'c' first place.
the proper algorithm more complex, can see what's wrong in solution.
Comments
Post a Comment