# Score of a String
**Difficulty:** EASY
[External](https://leetcode.com/problems/score-of-a-string)
Canonical: https://scaleengineer.com/dsa/problems/score-of-a-string
**Data structures:** String
---
## Problem
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.

# Approaches
## Recursive Approach
This approach uses recursion to solve the problem. A helper function is defined that processes the string one character pair at a time. The score for the current pair is calculated and added to the result of the recursive call for the rest of the string.
**Time:** O(N), where N is the length of the string `s`. The recursive function is called N-1 times, and each call performs a constant number of operations. · **Space:** O(N) in the worst case. This is due to the recursion depth, as each function call adds a new frame to the call stack. The maximum depth of the recursion is N.
**Pros:** Provides a functional, declarative way to express the solution.; Can be a good way to break down problems into smaller subproblems.
**Cons:** Less efficient in terms of space compared to an iterative solution due to the call stack overhead.; For very long strings (not an issue with the given constraints), it could lead to a `StackOverflowError`.; Can be less intuitive than a simple loop for this particular problem.
### Explanation
The core idea is to break the problem down into smaller, self-similar subproblems. We can define a function that calculates the score for a substring starting at a given index.

*   **Algorithm:**
    1.  Define a recursive function, let's call it `calculateScore(s, index)`.
    2.  **Base Case:** If the `index` reaches the last character (`s.length() - 1`), it means we've processed all pairs, so we return 0.
    3.  **Recursive Step:** The function calculates the absolute difference between the character at `index` and the character at `index + 1`. It then adds this difference to the result of a recursive call to `calculateScore` with the next index (`index + 1`).
    4.  The main function initiates the process by calling `calculateScore(s, 0)`.

*   **Code Snippet:**
```java
class Solution {
    public int scoreOfString(String s) {
        return calculateScoreRecursive(s, 0);
    }

    private int calculateScoreRecursive(String s, int index) {
        // Base case: If we are at the last character, there are no more pairs to consider.
        if (index == s.length() - 1) {
            return 0;
        }

        // Calculate the score for the current adjacent pair.
        int currentDifference = Math.abs(s.charAt(index) - s.charAt(index + 1));

        // Recursively call for the next pair and add it to the current score.
        return currentDifference + calculateScoreRecursive(s, index + 1);
    }
}
```
### Algorithm
*   Define a recursive function, let's call it `calculateScore(s, index)`.
*   **Base Case:** If the `index` reaches the second-to-last position (`s.length() - 1`), it means we've processed all pairs, so we return 0.
*   **Recursive Step:** The function calculates the absolute difference between the character at `index` and the character at `index + 1`. It then adds this difference to the result of a recursive call to `calculateScore` with the next index (`index + 1`).
*   The main function initiates the process by calling `calculateScore(s, 0)`.

## Single Pass Iteration
This is the most direct and optimal approach. We iterate through the string once, from the first character to the second-to-last. In each step, we calculate the absolute difference of ASCII values between the current character and the next one, and add this difference to a running total.
**Time:** O(N), where N is the length of the string `s`. We iterate through the string's characters once in a single loop that runs N-1 times. · **Space:** O(1). We only use a constant amount of extra space for variables like `score` and the loop counter `i`, regardless of the input string's size.
**Pros:** Optimal time complexity as we must examine each character pair once.; Optimal space complexity, using only a few variables.; Very simple, readable, and easy to implement.
**Cons:** There are no significant disadvantages to this approach as it is the most efficient solution for this problem.
### Explanation
The problem can be solved efficiently by iterating through the string and accumulating the score. We only need to look at each adjacent pair of characters once.

*   **Algorithm:**
    1.  Initialize an integer variable `score` to 0. This variable will accumulate the total score.
    2.  Loop through the string from the first character (index 0) up to the second-to-last character (index `s.length() - 2`). Let the loop variable be `i`.
    3.  Inside the loop, access the current character `s.charAt(i)` and the next character `s.charAt(i + 1)`.
    4.  Calculate the absolute difference of their ASCII values using `Math.abs(s.charAt(i) - s.charAt(i + 1))`. In Java, `char` types can be implicitly converted to `int` for arithmetic operations.
    5.  Add this calculated difference to the `score` variable.
    6.  After the loop completes, the `score` variable holds the final result. Return `score`.

*   **Code Snippet:**
```java
class Solution {
    public int scoreOfString(String s) {
        int score = 0;
        for (int i = 0; i < s.length() - 1; i++) {
            // Get the ASCII values of adjacent characters and add their absolute difference to the score.
            score += Math.abs(s.charAt(i) - s.charAt(i + 1));
        }
        return score;
    }
}
```
### Algorithm
*   Initialize an integer variable `score` to 0.
*   Loop through the string from index `i = 0` to `s.length() - 2`.
*   In each iteration, calculate the absolute difference between `s.charAt(i)` and `s.charAt(i + 1)`.
*   Add the difference to the `score`.
*   Return the final `score` after the loop.

# Solutions
### CSharp

```csharp
public class Solution {
    public int ScoreOfString(string s) {
        int ans = 0;
        for (int i = 1; i < s.Length; ++i) {
            ans += Math.Abs(s[i] - s[i - 1]);
        }
        return ans;
    }
}
```

### Java

```java
class Solution {
public
  int scoreOfString(String s) {
    int ans = 0;
    for (int i = 1; i < s.length(); ++i) {
      ans += Math.abs(s.charAt(i - 1) - s.charAt(i));
    }
    return ans;
  }
}

```

### CPP

```cpp
class Solution {
public:
  int scoreOfString(string s) {
    int ans = 0;
    for (int i = 1; i < s.size(); ++i) {
      ans += abs(s[i] - s[i - 1]);
    }
    return ans;
  }
};

```

### Python

```python
class Solution:
    def scoreOfString(self, s: str) -> int: return sum(abs(a - b)
                                                       for a, b in pairwise(map(ord, s)))

```
