The Love-Letter Mystery

Sort by

recency

|

987 Discussions

|

  • + 0 comments

    Step 1: Convert each character in the string to its ASCII value using ord(). Step 2: Use two pointers (st and en) to compare characters from the start and end of the string. Step 3: For each mismatch, calculate the difference in ASCII values and add it to the count. Step 4: Return the total number of operations needed to make the string a palindrome.

    def theLoveLetterMystery(s): # Convert each character to its ASCII value res = [ord(char) for char in s]

    # Initialize pointers and operation counter
    st = 0
    en = len(res) - 1
    count = 0
    
    # Compare characters from both ends
    while st < en:
        count += abs(res[st] - res[en])
        st += 1
        en -= 1
    
    return count
    

    `

  • + 0 comments

    This problem reminds me of how we sometimes make small changes for love—just like in frases de amor para mi esposo, where every word matters to make someone feel special. In this challenge, each letter change counts too, turning the message into something more beautiful... like a romantic palindrome!

  • + 0 comments

    Here is a python solution in O(n) time and O(1) space:

    def theLoveLetterMystery(s):
        letters = "abcdefghijklmnopqrstuvwxyz"
        
        i = 0
        j = len(s) - 1
        
        change_count = 0
        
        while i < j:
            if s[i] == s[j]:
                i += 1
                j -= 1
            else:
                idx_i = letters.index(s[i])
                idx_j = letters.index(s[j])
                temp_count = abs(idx_j - idx_i)
                
                change_count += temp_count
                i += 1
                j -= 1
            
        return change_count
    
  • + 0 comments

    C++

    int theLoveLetterMystery(string s)
    {
        int count{0};
        for (int i = s.length() - 1; i >= s.length() / 2; i--)
            count += abs(s[i] - s[s.length() - 1 - i]);
            
        return count;
    }
    
  • + 0 comments

    Java:

    public static int theLoveLetterMystery(String s) {
        int left = 0;
        int right = s.length() - 1;
        int retVal = 0;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                retVal += Math.abs((int) s.charAt(right) - (int) s.charAt(left));
            }
            ++left;
            --right;
        }
        return retVal;
    }