Score of a String

easy string ascii absolute difference

Problem

You are given a string s. Its score is the sum of the absolute difference between the ASCII values of every pair of adjacent characters. For each index i from 0 to len(s) − 2, add |ASCII(s[i]) − ASCII(s[i+1])|. Return the total score.

Inputs = "hello"
Output13
ASCII: h=104, e=101, l=108, l=108, o=111. Score = |104−101| + |101−108| + |108−108| + |108−111| = 3 + 7 + 0 + 3 = 13.

def scoreOfString(s):
    total = 0
    # add |ASCII gap| for each adjacent pair
    for i in range(len(s) - 1):
        total += abs(ord(s[i]) - ord(s[i + 1]))
    return total
function scoreOfString(s) {
  let total = 0;
  // add |ASCII gap| for each adjacent pair
  for (let i = 0; i < s.length - 1; i++) {
    total += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1));
  }
  return total;
}
int scoreOfString(String s) {
    int total = 0;
    // add |ASCII gap| for each adjacent pair
    for (int i = 0; i < s.length() - 1; i++) {
        total += Math.abs(s.charAt(i) - s.charAt(i + 1));
    }
    return total;
}
int scoreOfString(string s) {
    int total = 0;
    // add |ASCII gap| for each adjacent pair
    for (int i = 0; i < (int)s.size() - 1; i++) {
        total += abs(s[i] - s[i + 1]);
    }
    return total;
}
Time: O(n) Space: O(1)