Loading
Leetcode / 3110. Score of a String

Pick a programming language:

Here is the source code for the solution to this problem.

class Solution
{
    int ScoreOfString(string s) {
        int score = 0;
        for (var i = 0; i < s.Length - 1; i++)
        {
            int difference = (int)s[i] - (int)s[i + 1];
            if (difference > 0)
            {
                score += difference;
            }
            else
            {
                score -= difference;
            }
        }
        return score;
    }

    void AssertEqual(int actual, int expected)
    {
        if (actual != expected)
        {
            throw new System.Exception("Expected " + expected + ", but got " + actual);
        }
    }

    void Test()
    {
        AssertEqual(ScoreOfString("hello"), 13);
        AssertEqual(ScoreOfString("zaz"), 50);
    }

    public static void Main()
    {
        new Solution().Test();
    }
}
class Solution {
    public int scoreOfString(String s) {
        int score = 0;

        for (int i = 0; i < s.length() - 1; i++) {
            int difference = s.codePointAt(i) - s.codePointAt(i + 1);
            if (difference > 0) {
                score += difference;
            }
            else {
                score -= difference;
            }
        }

        return score;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: