【LetMeFly】3498.字符串的反转度:一次遍历
力扣题目链接:https://leetcode.cn/problems/reverse-degree-of-a-string/
给你一个字符串 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 <= 1000s仅包含小写字母。
解题方法:一次遍历
遍历字符串,下标为 i i i的字符c累加到答案中的值为 ( i + 1 ) × ( 26 − ( c − ′ a ′ ) ) (i+1) \times (26 - (c - 'a')) (i+1)×(26−(c−′a′))。
- 时间复杂度 O ( l e n ( s ) ) O(len(s)) O(len(s))
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
cpp
/*
* @LastEditTime: 2026-09-20 10:27:58
*/
class Solution {
public:
int reverseDegree(const string& s) {
int ans = 0;
for (int i = 0, n = s.size(); i < n; i++) {
// cout << (27 - s[i] + 'a') << " * " << i + 1 << endl;
ans += (i + 1) * (26 - s[i] + 'a');
}
return ans;
}
};
Python
python
'''
LastEditTime: 2026-09-20 10:42:23
'''
class Solution:
def reverseDegree(self, s: str) -> int:
return sum((i + 1) * (26 - ord(c) + ord('a')) for i, c in enumerate(s))
Java
java
/*
* @LastEditTime: 2026-09-20 10:40:05
*/
class Solution {
public int reverseDegree(String s) {
int ans = 0;
for (int i = 0; i < s.length(); i++) {
ans += (i + 1) * (26 - s.charAt(i) + 'a');
}
return ans;
}
}
Go
go
/*
* @LastEditTime: 2026-09-20 10:34:15
*/
package main
func reverseDegree(s string) (ans int) {
for i, c := range s {
ans += (i + 1) * (26 - int(c - 'a'))
}
return
}
Rust
rust
/*
* @LastEditTime: 2026-09-20 10:44:41
*/
impl Solution {
pub fn reverse_degree(s: String) -> i32 {
let mut ans = 0;
for (i, c) in s.chars().enumerate() {
ans += (i as i32 + 1) * (26 - c as i32 + 'a' as i32);
}
ans
}
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源