Leetcode 3110: Score of a String

grid47
grid47
Exploring patterns and algorithms
Jan 1, 2024 4 min read

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 the string s.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s of length n.
Example: s = "abc"
Constraints:
• 2 <= s.length <= 100
• s consists only of lowercase English letters
Output: Return the score of the string s.
Example: Output: 3
Constraints:
Goal: Calculate the score of the string by summing the absolute differences between ASCII values of adjacent characters.
Steps:
• 1. Initialize a variable to store the sum of absolute differences.
• 2. Loop through the string, comparing each pair of adjacent characters.
• 3. For each pair, compute the absolute difference in ASCII values and add it to the sum.
• 4. Return the total sum as the score.
Goal: The problem constraints limit the string length and characters.
Steps:
• 2 <= s.length <= 100
• s consists only of lowercase English letters
Assumptions:
• The input will always contain at least two characters.
• The string will only contain lowercase English letters.
Input: s = "abc"
Explanation: The ASCII values of the characters are: 'a' = 97, 'b' = 98, 'c' = 99. The score is |97 - 98| + |98 - 99| = 3.

Input: s = "zyx"
Explanation: The ASCII values of the characters are: 'z' = 122, 'y' = 121, 'x' = 120. The score is |122 - 121| + |121 - 120| = 6.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus