Minimum Number of Operations to Make String Sorted
You are given a string s (0-indexed). You are asked to perform the following operation on s until 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 10^9 + 7.
Example 1
Input
s = "cba"Output
5The operation sequence takes 5 steps to transform
"cba" into the sorted string "abc".Example 2
Input
s = "aabaa"Output
2The operation sequence takes 2 steps to transform
"aabaa" into the sorted string "aaaab".Constraints
- 1 <= s.length <= 3000
- s consists only of lowercase English letters.