3863. Minimum Operations to Sort a String
You are given a string s consisting of lowercase English letters.
In one operation, you can select any substring of s that is not the entire string and sort it in non-descending alphabetical order.
Return the minimum number of operations required to make s sorted in non-descending order. If it is not possible, return -1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: int minOperations(string s) { int n = s.length(); if(n == 1) return 0; if(n == 2) return s[0] > s[1] ? -1 : 0; string S = s; sort(begin(S), end(S)); if(S == s) return 0; if(S.front() == s.front() or S.back() == s.back()) return 1; string SS = s; sort(begin(SS) + 1, end(SS)); sort(begin(SS), end(SS) - 1); if(SS == S) return 2; SS = s; sort(begin(SS), end(SS) - 1); sort(begin(SS) + 1, end(SS)); if(SS == S) return 2; return 3; } };
|