Home  >  Article  >  Java  >  Leetcode — Score of a String

Leetcode — Score of a String

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 13:56:02802browse

Leetcode — 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;
    }
}

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! :)

The above is the detailed content of Leetcode — Score of a String. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn