3498. 字符串的反转度
题目描述
给你一个字符串 s
,计算其 反转度。
反转度的计算方法如下:
- 对于每个字符,将其在 反转 字母表中的位置(
'a'
= 26,'b'
= 25, ...,'z'
= 1)与其在字符串中的位置(下标从1 开始)相乘。 - 将这些乘积加起来,得到字符串中所有字符的和。
返回 反转度。
示例 1:
输入: s = "abc"
输出: 148
解释:
字母 | 反转字母表中的位置 | 字符串中的位置 | 乘积 |
---|---|---|---|
'a' |
26 | 1 | 26 |
'b' |
25 | 2 | 50 |
'c' |
24 | 3 | 72 |
反转度是 26 + 50 + 72 = 148
。
示例 2:
输入: s = "zaza"
输出: 160
解释:
字母 | 反转字母表中的位置 | 字符串中的位置 | 乘积 |
---|---|---|---|
'z' |
1 | 1 | 1 |
'a' |
26 | 2 | 52 |
'z' |
1 | 3 | 3 |
'a' |
26 | 4 | 104 |
反转度是 1 + 52 + 3 + 104 = 160
。
提示:
1 <= s.length <= 1000
s
仅包含小写字母。
解法
方法一:模拟
我们可以模拟字符串中每个字符的反转度。对于每个字符,我们计算它在反转字母表中的位置,然后乘以它在字符串中的位置,最后将所有结果相加即可。
时间复杂度 $O(n)$,其中 $n$ 是字符串的长度。空间复杂度 $O(1)$。
Python3
class Solution:
def reverseDegree(self, s: str) -> int:
ans = 0
for i, c in enumerate(s, 1):
x = 26 - (ord(c) - ord("a"))
ans += i * x
return ans
Java
class Solution {
public int reverseDegree(String s) {
int n = s.length();
int ans = 0;
for (int i = 1; i <= n; ++i) {
int x = 26 - (s.charAt(i - 1) - 'a');
ans += i * x;
}
return ans;
}
}
C++
class Solution {
public:
int reverseDegree(string s) {
int n = s.length();
int ans = 0;
for (int i = 1; i <= n; ++i) {
int x = 26 - (s[i - 1] - 'a');
ans += i * x;
}
return ans;
}
};
Go
func reverseDegree(s string) (ans int) {
for i, c := range s {
x := 26 - int(c-'a')
ans += (i + 1) * x
}
return
}
TypeScript
function reverseDegree(s: string): number {
let ans = 0;
for (let i = 1; i <= s.length; ++i) {
const x = 26 - (s.charCodeAt(i - 1) - 'a'.charCodeAt(0));
ans += i * x;
}
return ans;
}