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:

1.He can only reduce the value of a letter by 1, 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.


Example:

Input:  s="abc"
Output: 2

Approach

Java


public class LoveLetterMystery {
    public static void main(String[] args) {
        String s = "abc";

        int result = theLoveLetterMystery(s);
        System.out.println(result);
    }

    private static int theLoveLetterMystery(String str) {
        char s[] = str.toCharArray();
        int n = str.length();
        int i = 0, j = n - 1, cnt = 0;
        while (i < j) {
            if (s[i] == s[j]) {
                i++;
                j--;
            } else {
                if (s[i] > s[j]) {
                    cnt += s[i] - s[j];
                    s[i] = s[j];
                    i++;
                    j--;
                } else {
                    cnt += s[j] - s[i];
                    s[j] = s[i];
                    i++;
                    j--;
                }
            }
        }
        return cnt;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int theLoveLetterMystery(string s)
{
    int n = s.size();
    int i = 0j = n - 1cnt = 0;
    while (i < j)
    {
        if (s[i] == s[j])
        {
            i++;
            j--;
        }
        else
        {
            if (s[i] > s[j])
            {
                cnt += s[i] - s[j];
                s[i] = s[j];
                i++;
                j--;
            }
            else
            {
                cnt += s[j] - s[i];
                s[j] = s[i];
                i++;
                j--;
            }
        }
    }
    return cnt;
}

int main()
{

    string s = "abc";

    int result = theLoveLetterMystery(s);

    cout << result << "\n";

    return 0;
}


No comments:

Post a Comment