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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int score_of_string(const char* s) {
5 int score = 0;
6 for(int i = 0; s[i] && s[i+1]; i++) {
7 score += abs(s[i] - s[i+1]);
8 }
9 return score;
10}
11
12int main() {
13 char str[] = "hello";
14 printf("Score: %d\n", score_of_string(str));
15 return 0;
16}
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.
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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int recursive_score(const char* s, int index) {
5 if(s[index + 1] == '\0') return 0;
6 return abs(s[index] - s[index + 1]) + recursive_score(s, index + 1);
7}
8
9int main() {
10 char str[] = "hello";
11 printf("Score: %d\n", recursive_score(str, 0));
12 return 0;
13}
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.