Score of a String - Problem
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.
For example, if we have the string "hello", we calculate:
- |ASCII('h') - ASCII('e')| = |104 - 101| = 3
- |ASCII('e') - ASCII('l')| = |101 - 108| = 7
- |ASCII('l') - ASCII('l')| = |108 - 108| = 0
- |ASCII('l') - ASCII('o')| = |108 - 111| = 3
The total score would be 3 + 7 + 0 + 3 = 13.
Goal: Return the score of the given string s.
Input & Output
example_1.py β Basic Example
$
Input:
s = "hello"
βΊ
Output:
13
π‘ Note:
The adjacent character differences are: |'h'-'e'| = |104-101| = 3, |'e'-'l'| = |101-108| = 7, |'l'-'l'| = |108-108| = 0, |'l'-'o'| = |108-111| = 3. Total: 3+7+0+3 = 13
example_2.py β Single Character
$
Input:
s = "z"
βΊ
Output:
0
π‘ Note:
A single character has no adjacent characters, so the score is 0
example_3.py β Same Characters
$
Input:
s = "aaa"
βΊ
Output:
0
π‘ Note:
All characters are the same, so all adjacent differences are |'a'-'a'| = 0. Total: 0+0 = 0
Constraints
- 2 β€ s.length β€ 100
- s consists only of lowercase English letters
- ASCII values of lowercase letters range from 97 ('a') to 122 ('z')
Visualization
Tap to expand
Understanding the Visualization
1
Map Characters to Elevations
Each character becomes a checkpoint with ASCII value as elevation
2
Calculate Elevation Changes
Find absolute difference between consecutive checkpoint elevations
3
Sum Total Effort
Add all elevation changes to get total hiking effort (score)
Key Takeaway
π― Key Insight: We only need to visit each character once and calculate the ASCII difference with its immediate neighbor, making this an optimal O(n) solution.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code