3675. 转换字符串的最小操作次数
October 6, 2025 · View on GitHub
题目描述
给你一个仅由小写英文字母组成的字符串 s。
你可以执行以下操作任意次(包括零次):
-
选择字符串中出现的一个字符
c,并将 每个 出现的c替换为英文字母表中 下一个 小写字母。
返回将 s 转换为仅由 'a' 组成的字符串所需的最小操作次数。
注意:字母表是循环的,因此 'z' 的下一个字母是 'a'。
示例 1:
输入: s = "yz"
输出: 2
解释:
- 将
'y'变为'z',得到"zz"。 - 将
'z'变为'a',得到"aa"。 - 因此,答案是 2。
示例 2:
输入: s = "a"
输出: 0
解释:
- 字符串
"a"已经由'a'组成。因此,答案是 0。
提示:
1 <= s.length <= 5 * 105s仅由小写英文字母组成。
解法
方法一:一次遍历
根据题目描述,我们一定是先从字符 'b' 开始,依次将每个字符变为下一个字符,直到变为 'a'。因此,我们只需要统计字符串中距离 'a' 最远的字符与 'a' 的距离,即可得到答案。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
Python3
class Solution:
def minOperations(self, s: str) -> int:
return max((26 - (ord(c) - 97) for c in s if c != "a"), default=0)
Java
class Solution {
public int minOperations(String s) {
int ans = 0;
for (char c : s.toCharArray()) {
if (c != 'a') {
ans = Math.max(ans, 26 - (c - 'a'));
}
}
return ans;
}
}
C++
class Solution {
public:
int minOperations(string s) {
int ans = 0;
for (char c : s) {
if (c != 'a') {
ans = max(ans, 26 - (c - 'a'));
}
}
return ans;
}
};
Go
func minOperations(s string) (ans int) {
for _, c := range s {
if c != 'a' {
ans = max(ans, 26-int(c-'a'))
}
}
return
}
TypeScript
function minOperations(s: string): number {
let ans = 0;
for (const c of s) {
if (c !== 'a') {
ans = Math.max(ans, 26 - (c.charCodeAt(0) - 97));
}
}
return ans;
}