LeetCode 3498.字符串的反转度:一次遍历

【LetMeFly】3498.字符串的反转度:一次遍历

力扣题目链接:https://leetcode.cn/problems/reverse-degree-of-a-string/

给你一个字符串 s,计算其 反转度。

反转度的计算方法如下:

  1. 对于每个字符,将其在 反转 字母表中的位置('a' = 26, 'b' = 25, ..., 'z' = 1)与其在字符串中的位置(下标从1开始)相乘。
  2. 将这些乘积加起来,得到字符串中所有字符的和。

返回 反转度。

示例 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 仅包含小写字母。

解题方法:一次遍历

遍历字符串,下标为 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和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源

相关推荐
Pniubi2 天前
力扣2 . 两数相加
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode3401~3420题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode3421~3440题目解析
java·leetcode
LK_073 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi3 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
文丑颜不良啊3 天前
LeetCode3341~3360题目解析
java·leetcode
Rain的Java大神之路3 天前
把数组本身变成哈希表:原地哈希搞定 LeetCode 41「缺失的第一个正数」
java·后端·leetcode
Pniubi3 天前
力扣239.滑动窗口最大值(优先队列)
算法·leetcode·职场和发展
文丑颜不良啊4 天前
LeetCode3281~3300题目解析
java·leetcode
文丑颜不良啊4 天前
LeetCode3261~3280题目解析
java·leetcode