Score of a String

Solution

This solution directly calculates the score by iterating through adjacent characters and summing the absolute difference of their ASCII values.

Pseudocode

  1. Initialize a variable score to 0.
  2. Iterate through the input string s from the first character up to the second-to-last character.
  3. In each step, calculate the absolute difference between the ASCII value of the current character and the ASCII value of the next character.
  4. Add this difference to the score.
  5. After the loop completes, return the final score.

Code

class Solution:
    def scoreOfString(self, s: str) -> int:
        result = 0
        for i in range(len(s) - 1):
            result += abs(ord(s[i]) - ord(s[i + 1]))
        return result

Complexity Analysis

Tricks

  1. Adjacent Element Processing: The loop for i in range(len(s) - 1) is a classic pattern for iterating over adjacent pairs of elements in an array or string.
  2. Character-to-Integer Conversion: Use the ord() function to get the underlying integer (ASCII/Unicode) value of a character, allowing for arithmetic operations.