[LeetCode] Lexicographically Smallest String After Substring Operation

2734. Lexicographically Smallest String After Substring Operation

You are given a string s consisting of only lowercase English letters. In one operation, you can do the following:

  • Select any non-empty substring of s, possibly the entire string, then replace each one of its characters with the previous character of the English alphabet. For example, ‘b’ is converted to ‘a’, and ‘a’ is converted to ‘z’.

Return the lexicographically smallest string you can obtain after performing the above operation exactly once.

A substring is a contiguous sequence of characters in a string.

A string x is lexicographically smaller than a string y of the same length if x[i] comes before y[i] in alphabetic order for the first position i such that x[i] != y[i].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string smallestString(string s) {
bool ok = false;
for(int i = 0; i < s.length() and !ok; i++) {
if(s[i] == 'a') continue;
for(int j = i; j < s.length() and s[j] != 'a'; j++) {
s[j] -= 1;
}
ok = true;
}
if(!ok) s.back() = 'z';
return s;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/11/PS/LeetCode/lexicographically-smallest-string-after-substring-operation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.