Problem Name: Score of a String
Problem Statement:
Given a string `s`, calculate the score of the string where the score is defined as the sum of absolute differences between each pair of consecutive characters.
Input:
A single string `s` consisting of lowercase English letters.
Output:
An integer representing the score of the string.
Constraints:
- The length of the string `s` will be between 1 and 1000.
Example:
Input: "abcd"
Output: 3
Explanation: The score is calculated as |b-a| + |c-b| + |d-c| = 1 + 1 + 1 = 3.
Platforms:
Companies:
Topics Covered:
Strings,
Mathematics,
Loops,
Absolute Differences,
Character Manipulation
Solution:
Algorithm:
1. Initialize a variable `sum` to 0.
2. Loop through the string from the second character to the end.
3. For each character, calculate the absolute difference with the previous character and add it to `sum`.
4. Return the `sum` as the score of the string.
Code Implementation:
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int scoreOfString(char* s) {
int sum = 0;
for (int i = 1; i < strlen(s); i++) {
sum += abs(s[i] - s[i-1]);
}
return sum;
}
C++:
class Solution {
public:
int scoreOfString(string s) {
int sum = 0;
for(int i = 1; i < s.size(); i++) {
sum += abs(s[i] - s[i-1]);
}
return sum;
}
};
Java:
class Solution {
public int scoreOfString(String s) {
int sum = 0;
for (int i = 1; i < s.length(); i++) {
sum += Math.abs(s.charAt(i) - s.charAt(i - 1));
}
return sum;
}
}
Python:
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(ord(s[i]) - ord(s[i - 1])) for i in range(1, len(s)))
Complexity Analysis:
| Case | Time Complexity | Space Complexity |
|---|---|---|
| Worst Case | O(n) | O(1) |
| Average Case | O(n) | O(1) |
| Best Case | O(n) | O(1) |
