|
| 1 | +# [Score of a String](https://leetcode.com/problems/score-of-a-string/description) |
| 2 | + |
| 3 | +--- |
| 4 | + |
| 5 | +title: "Calculating the Score of a String Based on ASCII Differences" |
| 6 | +summary: "This post discusses a method to calculate the score of a string based on the absolute differences between the ASCII values of consecutive characters." |
| 7 | +date: "2024-06-01" |
| 8 | +modified_date: "2024-06-01" |
| 9 | +tags: ["JavaScript", "Algorithm", "String Manipulation"] |
| 10 | +slug: "calculating-score-string-ascii-differences" |
| 11 | + |
| 12 | +--- |
| 13 | + |
| 14 | +# Intuition |
| 15 | + |
| 16 | +<!-- Describe your first thoughts on how to solve this problem. --> |
| 17 | + |
| 18 | +To calculate the score of a string based on the differences in ASCII values between consecutive characters, we can use a simple iterative approach. The idea is to traverse the string, compute the absolute difference between the ASCII values of each pair of consecutive characters, and sum these differences to get the final score. |
| 19 | + |
| 20 | +# Approach |
| 21 | + |
| 22 | +<!-- Describe your approach to solving the problem. --> |
| 23 | + |
| 24 | +1. Initialize a variable `score` to store the cumulative score. |
| 25 | +2. Loop through the string from the first character to the second-last character. |
| 26 | +3. For each character, compute the absolute difference between its ASCII value and the ASCII value of the next character. |
| 27 | +4. Add this difference to the `score`. |
| 28 | +5. Return the `score` after processing the entire string. |
| 29 | + |
| 30 | +# Complexity |
| 31 | + |
| 32 | +- Time complexity: |
| 33 | + <!-- Add your time complexity here, e.g. $$O(n)$$ --> |
| 34 | + |
| 35 | + The time complexity of this approach is $$O(n)$$ because we need to iterate through the string once, where `n` is the length of the string. |
| 36 | + |
| 37 | +- Space complexity: |
| 38 | + <!-- Add your space complexity here, e.g. $$O(n)$$ --> |
| 39 | + The space complexity is $$O(1)$$ because we only use a constant amount of extra space regardless of the input size. |
| 40 | + |
| 41 | +# Code |
| 42 | + |
| 43 | +```javascript |
| 44 | +/** |
| 45 | + * @param {string} s |
| 46 | + * @return {number} |
| 47 | + */ |
| 48 | +function scoreOfString(s) { |
| 49 | + let score = 0; |
| 50 | + |
| 51 | + for (let i = 0; i < s.length - 1; i++) { |
| 52 | + score += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1)); |
| 53 | + } |
| 54 | + |
| 55 | + return score; |
| 56 | +} |
| 57 | +``` |
0 commit comments