Source : https://www.hackerrank.com/challenges/the-love-letter-mystery
James found a love letter that his friend Harry has written to his girlfriend. James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter into palindromes.
To do this, he follows two rules:
- He can only reduce the value of a letter by , i.e. he can change d to c, but he cannot change c to d or d to b.
- The letter a may not be reduced any further.
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.
For example, given the string , the following two operations are performed: cde → cdd → cdc.
Function Description
Complete the theLoveLetterMystery function in the editor below. It should return the integer representing the minimum number of operations needed to make the string a palindrome.
theLoveLetterMystery has the following parameter(s):
- s: a string
Input Format
The first line contains an integer , the number of queries.
The next lines will each contain a string .
Constraints
| s |
All strings are composed of lower case English letters, *ascii[a-z], with no spaces.
Output Format
A single line containing the minimum number of operations corresponding to each test case.
Sample Input
4
abc
abcba
abcd
cba
Sample Output
2042
Explanation
- For the first test case, abc → abb → aba.
- For the second test case, abcba is already a palindromic string.
- For the third test case, abcd → abcc → abcb → abca → abba.
- For the fourth test case, cba → bba → aba.
Source : https://www.hackerrank.com/challenges/the-love-letter-mystery
Solution
// Karthikalapati.blogspot.com | |
import java.util.Scanner; | |
// We compare ASCII values for pairs of characters. The 1st pair we consider is the 2 | |
// characters at opposite ends of the String. We then move inwards until we consider | |
// all palindromic pairs. | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
int T = scan.nextInt(); | |
while (T-- > 0) { | |
String str = scan.next(); | |
System.out.println(minimumOperations(str)); | |
} | |
scan.close(); | |
} | |
private static int minimumOperations(String str) { | |
int count = 0; | |
for (int i = 0; i < str.length() / 2; i++) { | |
count += Math.abs(str.charAt(i) - str.charAt(str.length() - 1 - i)); | |
} | |
return count; | |
} | |
} |
No comments:
Post a Comment