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.
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.
1using System;
2
3public class Program {
4 public static int ScoreOfString(string s) {
5 int score = 0;
6 for (int i = 0; i < s.Length - 1; i++) {
7 score += Math.Abs(s[i] - s[i + 1]);
8 }
9 return score;
10 }
11
12 public static void Main() {
13 string str = "hello";
14 Console.WriteLine("Score: " + ScoreOfString(str));
15 }
16}
In this C# program, the method ScoreOfString
calculates the score by looping over the string s
and computing the absolute difference between successive characters using the Math.Abs
function.
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.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), due to the recursion stack.
1def recursive_score(s, index=0):
2 if index >= len(s) - 1:
3 return 0
4 return abs(ord(s[index]) - ord(s[index + 1])) + recursive_score(s, index + 1)
5
6print('Score:', recursive_score('hello'))
In this Python function recursive_score
, recursion is utilized to process the string by calculating the difference for the current character with the next, and summing it with the result of the recursive call.