Given a string s consisting of lowercase English letters. Perform the following operation:
Select any non-empty substring then replace every letter of the substring with the preceding letter of the English alphabet. For example, ‘b’ is converted to ‘a’, and ‘a’ is converted to ‘z’.
Return the lexicographically smallest string after performing the operation.
Input: s ="acbbc"Output: "abaab"Explanation:
Perform the operation on the substring starting at index 1, and ending at
index 4 inclusive.#### Example 4Input: s ="leetcode"Output: "kddsbncd"Explanation:
Perform the operation on the entire string.
The lexicographically smallest string can be obtained by decrementing the first contiguous substring of non-‘a’ characters from the left. This is because changing ‘a’ to ‘z’ makes the string larger, so we want to avoid that. If all characters are ‘a’, decrement the last character.
classSolution {
public: string smallestString(string s) {
int n = s.size(), i =0;
while (i < n && s[i] =='a') i++;
if (i == n) {
s[n-1] ='z';
return s;
}
while (i < n && s[i] !='a') {
s[i] = s[i] -1;
i++;
}
return s;
}
};
classSolution {
public String smallestString(String s) {
char[] arr = s.toCharArray();
int i = 0, n = arr.length;
while (i < n && arr[i]=='a') i++;
if (i == n) {
arr[n-1]='z';
returnnew String(arr);
}
while (i < n && arr[i]!='a') {
arr[i]--;
i++;
}
returnnew String(arr);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsmallestString(s: String): String {
val arr = s.toCharArray()
var i = 0while (i < arr.size && arr[i] =='a') i++if (i == arr.size) {
arr[arr.size-1] = 'z'return String(arr)
}
while (i < arr.size && arr[i] !='a') {
arr[i] = (arr[i] - 1).toChar()
i++ }
return String(arr)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defsmallestString(self, s: str) -> str:
arr = list(s)
i =0while i < len(arr) and arr[i] =='a':
i +=1if i == len(arr):
arr[-1] ='z'return''.join(arr)
while i < len(arr) and arr[i] !='a':
arr[i] = chr(ord(arr[i]) -1)
i +=1return''.join(arr)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnsmallest_string(s: String) -> String {
letmut arr: Vec<char>= s.chars().collect();
letmut i =0;
while i < arr.len() && arr[i] =='a' {
i +=1;
}
if i == arr.len() {
arr[arr.len()-1] ='z';
return arr.into_iter().collect();
}
while i < arr.len() && arr[i] !='a' {
arr[i] = ((arr[i] asu8) -1) aschar;
i +=1;
}
arr.into_iter().collect()
}
}