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:
  1. 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.
  2. 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

Question from hackerrank.

Solution in C# - 

class Solution {
    static int theLoveLetterMystery(string s) {    
        int ans = 0;
        int len = s.Length/2;
        string s1 = s.Substring(0,len);
        string s2 = s.Substring(len);
        //Console.WriteLine(s1+" "+s2);
        for(int i=0, j=s2.Length-1 ; i<s1.Length && j>=0 ; i++, j--)
        {
            ans += Math.Abs(s1[i]-s2[j]);
        }        
        return ans;
    }
    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
        int q = Convert.ToInt32(Console.ReadLine());
        for (int qItr = 0; qItr < q; qItr++) {
            string s = Console.ReadLine();
            int result = theLoveLetterMystery(s);
            textWriter.WriteLine(result);
        }
        textWriter.Flush();
        textWriter.Close();
    }
}

Post a Comment

Previous Post Next Post