Score of a String Solution in Java


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

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

    return ans;
  }
}

Problem Description

Welcome to the whimsical world of string scoring! Imagine you’re at a party, and every time two friends (characters) talk, they either get along splendidly or have a minor disagreement. The score of their conversation is determined by how different they are from each other. If they are best buddies (the same character), they score a big fat zero. If they are as different as cats and dogs (different characters), they score a point equal to the absolute difference of their ASCII values.

In simpler terms, the problem asks you to calculate the total score of a string based on the differences between adjacent characters. So, if you’ve ever wondered how to quantify the drama in your life, this is your chance!

Approach

The approach is as straightforward as it gets! The code iterates through the string, comparing each character with its predecessor. For every pair of adjacent characters, it calculates the absolute difference of their ASCII values and adds it to the total score. It’s like a friendly competition where every character tries to outdo its neighbor!

Time and Space Complexity

Complexity Type 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

Let’s say you’re at a family reunion, and you’re trying to score the conversations between your relatives. Uncle Bob and Aunt Sue are having a chat, and they both have very different opinions on pineapple on pizza. The score of their conversation would be the absolute difference in their opinions (or ASCII values, in our case). The more different they are, the higher the score!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Java