You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s.
Example 1:
Input: s = "code"
Output: 24Explanation: The ASCII values of the characters in the given string are: 'c' = 99, 'o' = 111, 'd' = 100, and 'e' = 101. The score of s will be: |111 - 99| + |100 - 111| + |101 - 100|.
Example 2:
Input: s = "neetcode"
Output: 65Constraints:
2 <= s.length <= 100s is made up of lowercase English letters.Before attempting this problem, you should be comfortable with:
The score of a string is defined as the sum of absolute differences between adjacent characters' ASCII values. Since we need to compare each character with its neighbor, we simply walk through the string once, computing the difference between consecutive characters and accumulating the result in res.
res to store the running total.0 to n - 2:i, compute the absolute difference between the ASCII values of s[i] and s[i + 1].res.res as the final answer.A frequent mistake is iterating to n instead of n - 1, causing an index out of bounds error when accessing s[i + 1]. Since you compare adjacent pairs, the loop should run from 0 to len(s) - 2 inclusive, processing n - 1 pairs for a string of length n.
Some solutions subtract ASCII values without taking the absolute value, resulting in negative contributions to the score. The problem requires the sum of absolute differences, so always wrap the subtraction with abs() to handle cases where s[i] > s[i + 1].