Medium
You are given a string s
consisting only of lowercase English letters.
You can perform the following operation any number of times (including zero):
c
in the string and replace every occurrence of c
with the next lowercase letter in the English alphabet.Return the minimum number of operations required to transform s
into a string consisting of only 'a'
characters.
Note: Consider the alphabet as circular, thus 'a'
comes after 'z'
.
Example 1:
Input: s = âyzâ
Output: 2
Explanation:
'y'
to 'z'
to get "zz"
.'z'
to 'a'
to get "aa"
.Example 2:
Input: s = âaâ
Output: 0
Explanation:
"a"
only consists of 'a'
characters. Thus, the answer is 0.Constraints:
1 <= s.length <= 5 * 105
s
consists only of lowercase English letters.public class Solution {
public int minOperations(String s) {
int n = s.length();
int ans = 0;
for (int i = 0; i < n; i++) {
final char c = s.charAt(i);
if (c != 'a') {
int ops = 'z' - c + 1;
if (ops > ans) {
ans = ops;
}
if (ops == 25) {
break;
}
}
}
return ans;
}
}