Skip to content

3498. Reverse Degree of a String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int reverseDegree(string s) {
    int ans = 0;
    for (int i = 0; i < s.length(); ++i) {
      const int reversePos = 26 - (s[i] - 'a');
      ans += reversePos * (i + 1);
    }
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int reverseDegree(String s) {
    int ans = 0;
    for (int i = 0; i < s.length(); ++i) {
      final int reversePos = 26 - (s.charAt(i) - 'a');
      ans += reversePos * (i + 1);
    }
    return ans;
  }
}
1
2
3
4
class Solution:
  def reverseDegree(self, s: str) -> int:
    return sum((26 - (ord(c) - ord('a'))) * (i + 1)
               for i, c in enumerate(s))