Leetcode — 3110. Score of a String

bendlmp

Ben Pereira

Posted on November 2, 2024

Leetcode — 3110. Score of a String

It’s an easy problem from leet code with the description being:

You are given a string s. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s.

Example 1:
Input: s = “hello”
Output: 13

Explanation:
The ASCII values of the characters in s are: 'h' = 104, 'e' = 101, 'l' = 108, 'o' = 111. So, the score of s would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13.

Example 2:
Input: s = “zaz”
Output: 50

Explanation:
The ASCII values of the characters in s are: 'z' = 122, 'a' = 97. So, the score of s would be |122 - 97| + |97 - 122| = 25 + 25 = 50.
Constraints:

2 <= s.length <= 100
s consists only of lowercase English letters.

There is no much to do into this, you basically have iterate and grab two characters of the string and subtract first to the second and get the absolute of it and add into a sum variable.

It’s important to start on second index to avoid out of bounds exception.

To get char as ascii you basically cast as integer and that would do.

class Solution {
    public int scoreOfString(String s) {
        int sum = 0;
        for(int i=1;i<s.length();i++){
            final int first  = (int) s.charAt(i - 1);
            final int second = (int) s.charAt(i);
            sum += Math.abs(first - second);
        }
        return sum;
    }
}
Enter fullscreen mode Exit fullscreen mode

Runtime: 1 ms, faster than 99.37% of Java online submissions for Score of a String.
Memory Usage: 42 MB, less than 30.18% of Java online submissions for Score of a String.

That’s it! If there is anything thing else to discuss feel free to drop a comment, if I missed anything let me know so I can update accordingly.

Until next post! :)

💖 💪 🙅 🚩
bendlmp
Ben Pereira

Posted on November 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related