Class Solution
-
- All Implemented Interfaces:
public final class Solution1830 - Minimum Number of Operations to Make String Sorted.
Hard
You are given a string
s( 0-indexed ). You are asked to perform the following operation onsuntil you get a sorted string:Find the largest index
isuch that1 <= i < s.lengthands[i] < s[i - 1].Find the largest index
jsuch thati <= j < s.lengthands[k] < s[i - 1]for all the possible values ofkin the range[i, j]inclusive.Swap the two characters at indices
i - 1andj.Reverse the suffix starting at index
i.
Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo <code>10<sup>9</sup> + 7</code>.
Example 1:
Input: s = "cba"
Output: 5
Explanation: The simulation goes as follows: Operation 1: i=2, j=2. Swap s1 and s2 to get s="cab", then reverse the suffix starting at 2. Now, s="cab".
Operation 2: i=1, j=2. Swap s0 and s2 to get s="bac", then reverse the suffix starting at 1. Now, s="bca".
Operation 3: i=2, j=2. Swap s1 and s2 to get s="bac", then reverse the suffix starting at 2. Now, s="bac".
Operation 4: i=1, j=1. Swap s0 and s1 to get s="abc", then reverse the suffix starting at 1. Now, s="acb".
Operation 5: i=2, j=2. Swap s1 and s2 to get s="abc", then reverse the suffix starting at 2. Now, s="abc".
Example 2:
Input: s = "aabaa"
Output: 2
Explanation: The simulation goes as follows:
Operation 1: i=3, j=4. Swap s2 and s4 to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".
Operation 2: i=4, j=4. Swap s3 and s4 to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".
Constraints:
1 <= s.length <= 3000sconsists only of lowercase English letters.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntegermakeStringSorted(String s)-
-
Method Detail
-
makeStringSorted
final Integer makeStringSorted(String s)
-
-
-
-