Score of a String

Updated on 15 July, 2025
Score of a String header image

Problem Statement

In this problem, you are provided with a string s. Your task is to calculate and return the score of this string. The score is determined by summing up the absolute differences between the ASCII values of each pair of adjacent characters in the string. Essentially, you need to traverse through the string, compare each character to its neighbor, compute the difference in their ASCII values, take the absolute value of these differences, and sum them all to obtain the final score. This problem tests your ability to string manipulate and utilize basic numerical operations in programming.

Examples

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.

Approach and Intuition

To solve this problem efficiently, let's break down the steps needed, based on the given examples and constraints.

  1. Initialize a variable to store the score of the string, typically set to 0 at the start.
  2. Iterate through the string using a loop that goes from the first character to the second to last character, since we'll be comparing each character to the next one.
  3. For each character in the string:
    • Retrieve the ASCII value of the current character and the next character.
    • Compute the absolute difference between these two ASCII values.
    • Add the absolute difference to the score accumulator.
  4. Continue this process until all pairs of adjacent characters have been evaluated.
  5. Return the total score obtained.

Key points to consider:

  • Ensure efficient access to the string's characters by using appropriate string indexing.
  • Make use of Python's abs() function for calculating the absolute difference.
  • The constraints indicate that the solution must handle strings up to a length of 100, implying the need for an efficient approach, but given the problem's limitations (only lowercase letters and relatively short maximum length), a straightforward linear iteration over the string is both suitable and efficient.

When implemented correctly, this approach will accurately compute the score by following the rule of summing up the absolute ASCII differences of adjacent characters, as clearly demonstrated in the examples provided.

Solutions

  • C++
cpp
class Solution {
public:
    int calculateScore(string str) {
        int total = 0;
        for (int idx = 0; idx < str.length() - 1; ++idx) {
            total += abs(str[idx] - str[idx + 1]);
        }
        return total;
    }
};

The solution provided is for calculating the "score" of a string, where the score is defined as the sum of the absolute differences between consecutive characters in the string. This can be useful for applications that need to measure how characters in a string vary consecutively, which might be useful for cryptography or text analysis tasks.

Here is a breakdown of how the code is structured and functions:

  • A class named Solution is defined.
  • Inside the Solution class, there is a public function called calculateScore which takes a string (named str) as its parameter.
  • The calculateScore function initializes an integer total to zero. This variable will hold the computed score.
  • A loop iterates through the string from the first character to the second last character.
    • During each iteration, the function calculates the absolute difference between the current character and the next character.
    • This absolute difference is then added to total.
  • After the loop completes, the function returns the total score.

Ensure to include the string library and understand basic operations like string length and character manipulation to utilize this code effectively.

  • Java
java
public class Solution {
    public int calculateScore(String input) {
        int totalScore = 0;
        for (int idx = 0; idx < input.length() - 1; idx++) {
            totalScore += Math.abs(input.charAt(idx) - input.charAt(idx + 1));
        }
        return totalScore;
    }
}

The provided Java program calculates the "score" of a string by determining the absolute difference between the ASCII values of consecutive characters in the string. The program contains a calculateScore method within the Solution class. Here's how the function works:

  • The method accepts a string parameter named input.
  • Initially, the totalScore variable is set to zero.
  • A for-loop runs from the start of the string to the second last character. In each iteration:
    • Calculate the absolute difference between the ASCII values of consecutive characters using Math.abs(input.charAt(idx) - input.charAt(idx + 1)).
    • Accumulate these differences in totalScore.
  • After completing the iterations through the string, totalScore, which holds the cumulative difference, is returned.

This method efficiently summarizes the total difference, providing a numeric "score" based on character proximity in terms of ASCII values, and it handles the operations in O(n) time complexity, where n is the number of characters in the input string minus one.

  • Python
python
class Solution:
    def compute_string_score(self, string: str) -> int:
        total_score = 0
        for idx in range(len(string) - 1):
            total_score += abs(ord(string[idx]) - ord(string[idx + 1]))
        return total_score

The provided Python code defines a class Solution with a method compute_string_score that calculates and returns the score of a given string. The score is computed by iterating through the string, and for each pair of consecutive characters, the absolute difference between their ASCII values is calculated and added to a cumulative total. This method effectively measures the total variation in character codes throughout the string. The final score represents the sum of these differences, which is returned at the end of the method.

Comments

No comments yet.