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.
1public class ScoreOfString {
2 public static int scoreOfString(String s) {
3 int score = 0;
4 for (int i = 0; i < s.length() - 1; i++) {
5 score += Math.abs(s.charAt(i) - s.charAt(i + 1));
6 }
7 return score;
8 }
9
10 public static void main(String[] args) {
11 String str = "hello";
12 System.out.println("Score: " + scoreOfString(str));
13 }
14}
This Java program defines a method scoreOfString
that calculates the score by iterating through the string and taking the absolute difference between adjacent characters in the string using the Math.abs
method.
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.
1public class ScoreOfString {
2 public static int recursiveScore(String s, int index) {
3 if (index >= s.length() - 1) return 0;
4 return Math.abs(s.charAt(index) - s.charAt(index + 1)) + recursiveScore(s, index + 1);
5 }
6
7 public static void main(String[] args) {
8 String str = "hello";
9 System.out.println("Score: " + recursiveScore(str, 0));
10 }
11}
This Java implementation uses recursion to calculate the score. The method recursiveScore
recursively handles characters, computing differences until the end of the string.