Site icon May's Notes

[LeetCode] 3110. Score of a String (JS)

LeetCode Sharing

題目

給你一個字串 s 。計算s相鄰字元的 ASCII 值之間的絕對差之和。

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.

解法

此解法不需要知道字母在ASCII中是多少,不過需要記得 string.charCodeAt() 這個方法

/**
 * @param {string} s
 * @return {number}
 */
var scoreOfString = function(s) {
    let sum = 0
    for (let i = 1; i < s.length; i++) {
        sum += Math.abs(s.charCodeAt(i - 1) - s.charCodeAt(i))
    }
    return sum
};
Exit mobile version