3110. Score of a String LeetCode Solution

In this guide, you will get 3110. Score of a String LeetCode Solution with the best time and space complexity. The solution to Score of a String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Score of a String solution in C++
  4. Score of a String solution in Java
  5. Score of a String solution in Python
  6. Additional Resources
3110. Score of a String LeetCode Solution image

Problem Statement of Score of a String

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.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

3110. Score of a String LeetCode Solution in C++

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

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

    return ans;
  }
};
/* code provided by PROGIEZ */

3110. Score of a String LeetCode 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;
  }
}
// code provided by PROGIEZ

3110. Score of a String LeetCode Solution in Python

class Solution:
  def scoreOfString(self, s: str) -> int:
    return sum(abs(ord(a) - ord(b))
               for a, b in itertools.pairwise(s))
# code by PROGIEZ

Additional Resources

See also  1281. Subtract the Product and Sum of Digits of an Integer LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.