Sort a string lexicographically by reversing a substring | C ++ program for the above approach ; Function to find the substring in S required to be reversed ; Stores the size of the string ; Stores the starting point of the substring ; Iterate over the string S while i < N ; Increment the value of i ; Stores the ending index of the substring ; If start <= 0 or i >= N ; If start >= 1 and i <= N ; Return the boolean value ; If start >= 1 ; Return the boolean value ; If i < N ; Return true if S [ start ] is less than or equal to S [ i ] ; Otherwise ; Function to check if it is possible to sort the string or not ; Stores the starting and the ending index of substring ; Stores whether it is possible to sort the substring ; Traverse the range [ 1 , N ] ; If S [ i ] is less than S [ i - 1 ] ; If flag stores true ; If adjust ( S , i , start , end ) return false ; Print - 1 ; Unset the flag ; Otherwise ; Print - 1 ; If start is equal to - 1 ; Update start and end ; Print the value of start and end ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool adjust ( string & S , int & i , int & start , int & end ) { int N = S . length ( ) ; start = i - 1 ; while ( i < N && S [ i ] < S [ i - 1 ] ) { i ++ ; } end = i - 1 ; if ( start <= 0 && i >= N ) return true ; if ( start >= 1 && i <= N ) { return ( S [ end ] >= S [ start - 1 ] && S [ start ] <= S [ i ] ) ; } if ( start >= 1 ) { return S [ end ] >= S [ start - 1 ] ; } if ( i < N ) { return S [ start ] <= S [ i ] ; } return false ; } void isPossible ( string & S , int N ) { int start = -1 , end = -1 ; bool flag = true ; for ( int i = 1 ; i < N ; i ++ ) { if ( S [ i ] < S [ i - 1 ] ) { if ( flag ) { if ( adjust ( S , i , start , end ) == false ) { cout << -1 << endl ; return ; } flag = false ; } else { cout << -1 << endl ; return ; } } } if ( start == -1 ) { start = end = 1 ; } cout << start << " ▁ " << end << " STRNEWLINE " ; } int main ( ) { string S = " abcyxuz " ; int N = S . length ( ) ; isPossible ( S , N ) ; return 0 ; }