1. Description
Given a string s containing lowercase English letters, make its characters non-decreasing alphabetically.
Each operation chooses a nonempty contiguous substring shorter than s and rearranges that substring into alphabetical order.
Return the fewest operations needed, or -1 if no sequence of allowed operations can sort s.
2. Example
Example 1
Input: s = “dog”
Output: 1
Explanation: Rearranging “og” as “go” changes the string to “dgo”, so one operation suffices.
Example 2
Input: s = “card”
Output: 2
Explanation: First rearrange “car” as “acr” to obtain “acrd”. Then rearrange “rd” as “dr” to obtain the sorted string “acdr”.
Example 3
Input: s = “gf”
Output: -1
Explanation: Only single-character substrings may be selected, and sorting them cannot change the string.
3. Constraints
- 1 <= s.length <= 10$^5$
- Every character of s is a lowercase English letter.
4. Solutions
Case Analysis
n = str.size()
Time complexity: O(n)
Space complexity: O(1)
| |