Score of a String Solution in C++


Problem Description

The “Score of a String” problem involves calculating the score of a string based on the absolute differences between the ASCII values of adjacent characters. Imagine you’re at a party, and every time someone says something awkward, you mentally note down how cringeworthy it was. The higher the score, the more you want to hide under the nearest table. Similarly, in this problem, the score reflects the “awkwardness” of the string based on its characters.

Code Solution


class Solution {
 public:
  int scoreOfString(string s) {
    int ans = 0;

    for (int i = 1; i < s.length(); ++i)
      ans += abs(s[i] - s[i - 1]);

    return ans;
  }
};
    

Approach

The approach is straightforward. We loop through the string, starting from the second character, and calculate the absolute difference between each character and its predecessor. This difference is then accumulated to give us the final score. It’s like counting how many times you cringed at that party!

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the string. We traverse the string once.
  • Space Complexity: O(1), as we are using a constant amount of space for the score variable.

Real-World Example

Imagine you're at a karaoke night, and your friend decides to sing a song. Each note they hit is like a character in the string. If they hit a high note followed by a low note, the score goes up, reflecting the "musical awkwardness" of the performance. The more off-key they are, the higher the score!

Similar Problems

If you enjoyed this problem, you might want to check out these related challenges:

  • 2-Sum Solution in C++
  • 3-Sum Solution in C++