2734. Lexicographically Smallest String After Substring Operation

Difficulty:
Related Topics:
Similar Questions:

Problem

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

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].

Example 1:

Input: s = "cbabc"
Output: "baabc"
Explanation: We apply the operation on the substring starting at index 0, and ending at index 1 inclusive.
It can be proven that the resulting string is the lexicographically smallest.

Example 2:

Input: s = "acbbc"
Output: "abaab"
Explanation: We apply the operation on the substring starting at index 1, and ending at index 4 inclusive.
It can be proven that the resulting string is the lexicographically smallest.

Example 3:

Input: s = "leetcode"
Output: "kddsbncd"
Explanation: We apply the operation on the entire string.
It can be proven that the resulting string is the lexicographically smallest.

Constraints:

Solution (Java)

class Solution {
    public String smallestString(String s) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        boolean replace = false;
        for (int i = 0; i < n; i++) {
            if(chars[i]=='a'){
                if(replace){
                    break;
                }
                continue;
            }
            replace = true;
            chars[i] = (char) (chars[i]-1);
        }
        if(!replace){
            chars[n-1] = 'z';
        }
        return new String(chars);
    }
}

Explain:

nope.

Complexity: