The problem goes like this.
Change the strings provided by user to form palindromes. To do this, 2 rules are:
(a) Reduce the value of a letter, e.g. Change 'd' to 'c', but cannot change 'c' to 'd'.
(b) In order to form a palindrome, you can repeatedly reduce the value of a letter until the letter becomes 'a'. Once a letter has been changed to 'a', it can no longer be changed.
Each reduction in the value of any letter is counted as a single operation. Find the minimum number of operations required to convert a given string into a palindrome.
This is a HackerRank problem: the-love-letter-mystery
While I was solving it, I made a lot of mistakes. I was using char *str[n]
and gets()
to input the string. I thought it would work, but I realised after long time that I am not actually allocating any space at all. Later I came up with 2-d array char[n][1000]
for storing the strings and scanf
seemed to work for me.
Here is my solution:
int main() {
int i, n, len, pos, ops, end;
scanf("%d",&n);
char str[n][10000];
char a,b;
for (i=0;i<n;i++) {
scanf("%s",str[i]);
}
for (i=0;i<n;i++) {
len = strlen(str[i]);
pos = 0;
end = len - 1;
ops = 0;
while ( pos < end) {
a = str[i][pos];
b = str[i][end];
if ( a != b ) {
if ( b > a )
ops = ops + (b -a);
else
ops = ops + (a -b);
}
pos++;
end--;
}
printf("%d\n", ops);
}
return 0;
}
This works perfectly. I also have to assume in the program that the strings can be of max length 1000 as that is one of the constraint.
How can I improve this solution without making it too complex?