Talentd
FleetCode

3110. Score of a String

Easy91.4% acceptance5 companies

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 = "hello"

Output: 13

Explanation:

The ASCII values of the characters in s are: 'h' = 104, 'e' = 101, 'l' = 108, 'o' = 111. So, the score of s would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13.

Example 2:

Input: s = "zaz"

Output: 50

Explanation:

The ASCII values of the characters in s are: 'z' = 122, 'a' = 97. So, the score of s would be |122 - 97| + |97 - 122| = 25 + 25 = 50.

Constraints:

  • 2 <= s.length <= 100
  • s consists only of lowercase English letters.

Topics

Hints open one at a time

Hint 1
Sum the difference between all the adjacent characters by just taking the absolute difference of their ASCII values.
3:35
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def scoreOfString(self, s: str) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"hello"
Input
"zaz"
Your code is saved on this device.Solution