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 <= 100s consists only of lowercase English letters.This approach involves iterating through the string and calculating the absolute difference between each pair of adjacent characters, summing these differences to get the total score for the string.
We can easily access the ASCII value of a character in most programming languages by either using a built-in function or converting the character to an integer type.
This C program defines a function score_of_string that takes a string s as input. The function iterates over the string characters using indices, calculating the absolute difference between each character and the next. These differences are summed to obtain the total score.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as no extra space is used apart from a few variables.
This approach involves using recursion to calculate the score of the string. The function will compute the difference for the first two characters and then call itself recursively for the remaining substring.
This method is more of a demonstration of recursion as it is less optimal than the iterative method due to function call overhead.
This C solution uses a recursive function recursive_score, which calculates the score from an index. The base condition checks for the end of the string, and the recursive call processes the remaining substring.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), due to the recursion stack.
| Approach | Complexity |
|---|---|
| Iterative ASCII Difference Calculation | Time Complexity: O(n), where n is the length of the string. |
| Recursive ASCII Difference Calculation | Time Complexity: O(n), where n is the length of the string. |
Encode and Decode Strings - Leetcode 271 • NeetCode • 381,920 views views
Watch 9 more video solutions →Practice Score of a String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor