Leetcode # 3110. Score of a String

Problem

https://leetcode.com/problems/score-of-a-string

Solution 1:重視速度

Time Complexity: O(len(s))
Space Complexity: O(len(s))
(The input and output generally do not count towards the space complexity.)

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

Solution 2:重視空間

Time Complexity: O(len(s))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

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

 

Last Updated on 2024/06/09 by A1go

目錄
Bitnami