Home > Umum > The Love-Letter Mystery

The Love-Letter Mystery

James found a love letter his friend Harry has written for 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 2 rules:

  1. He can reduce the value of a letter, e.g. he can change ‘d’ to ‘c’, but he cannot change ‘c’ to ‘d’.
  2. In order to form a palindrome, if he has to repeatedly reduce the value of a letter, he can do it 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.

Java Solution:

import java.util.Scanner;

public class LoveLetterMystery {

 public static void main(String[] args) { 
 Scanner in = new Scanner(System.in);
 int input = in.nextInt();
 String[] arrStr = new String[input];
 in.nextLine();
 for(int a = 0; a < input; a++) {
 arrStr[a] = in.nextLine();
 }
 for(int a = 0; a < arrStr.length; a++){
 System.out.println(stepProducePalindrome(arrStr[a]));
 }
 in.close();
 }
 
 private static int stepProducePalindrome(String input) {
 int charLength = (input.length() - 1);
 int front = 0;
 int back = charLength;
 int step = 0;
 while(front < back) {
 if(input.charAt(front) != input.charAt(back)) {
 step += Math.abs(input.charAt(front) - input.charAt(back));
 }
 front++;
 back --;
 }
 return step;
 }

}

Output:

Love letter

Reference:

https://www.hackerrank.com/challenges/the-love-letter-mystery

Categories: Umum Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: