Score of a String

Solution

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

Idea

Walk adjacent pairs with range(len(s) - 1) and sum abs(ord(a) - ord(b)). ord() gives the character's integer value.

Complexity

Time O(N), space O(1).


Related: LeetCode, Arrays and Hashing, Concatenation of Array, Contains Duplicate