Score of a String
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.
s = "hello"13def 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;
}
Explanation
This is a straightforward single pass over the string. Each lowercase letter has an ASCII code ('a' = 97, 'b' = 98, … 'z' = 122), and the score measures how much the codes jump between neighbours.
We walk an index i from 0 up to len(s) − 2. At each step we look at the pair s[i] and s[i+1], take the absolute difference of their codes, and add it to a running total. The absolute value means direction does not matter — an up-jump and a down-jump of the same size contribute equally.
There are exactly len(s) − 1 adjacent pairs, so the loop runs that many times. After the last pair, total holds the answer.
Example: for "hello" the codes are 104, 101, 108, 108, 111. The gaps are 3, 7, 0, 3, which sum to 13. For "zaz" the codes are 122, 97, 122, giving gaps 25 and 25 for a total of 50.