NeetCode #7LC-3110EasyArrays & Hashing
← Back to All Problems

#7 · #3110 · Score of a String(字符串的分数)

📌 Problem Statement & Constraints

Given a string s, return the score of the string: the sum of |s[i] - s[i+1]| over all adjacent pairs, using the alphabetical positions of the characters. Constraints: 1 <= s.length <= 100.

💡 Core Algorithmic Approaches

  1. This is a direct simulation; the only subtlety is converting characters to positions consistently.
  2. Use ord(ch) - ord('a') to map letters to 0-25. Because the subtraction is applied to both operands, the absolute difference is the same as with 1-26 positions.
  3. Sum the absolute differences over consecutive pairs.
  4. A single-character string has no adjacent pairs, so the answer is 0 -- the loop body never runs.

💻 Benchmark Python3 Implementation

class Solution:
    def scoreOfString(self, s: str) -> int:
        return sum(abs(ord(s[i]) - ord(s[i + 1])) for i in range(len(s) - 1))

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass over adjacent pairs.
💾 Space Complexity
O(1): a single accumulator.

⚠️ Interview Pitfalls & Follow-ups

  • Mixing 0-based and 1-based letter positions: as long as both operands use the same convention, the difference is identical, so either is fine -- just be consistent.
  • Forgetting abs: the difference can be negative when characters descend.
  • Using the numeric value of the character without subtracting ord('a'): the score would be scaled but, since both terms shift equally, the absolute difference is actually unchanged -- still, subtracting is clearer and safer.