-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_NextHigherPalindromicNumUsingTheSetOfDigits.cpp
81 lines (66 loc) · 1.92 KB
/
GFG_NextHigherPalindromicNumUsingTheSetOfDigits.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
https://practice.geeksforgeeks.org/problems/next-higher-palindromic-number-using-the-same-set-of-digits5859/1#
Next higher palindromic number using the same set of digits
*/
// { Driver Code Starts
//Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
string nextPalin_(string s) {
int n = s.length();
if(n<=3)
return "-1";
string left = s.substr(0, n/2);
if(next_permutation(left.begin(), left.end()) == false)
return "-1";
string right = left;
reverse(right.begin(), right.end());
if(n%2 == 1)
left += s[n/2];
return left+right;
}
string nextPalin(string s) {
int n = s.length();
if(n<=3)
return "-1";
int mid = n/2; // mid index
int rem = n&1; //n%2; //odd length
// find next permutation of string 1 to mid
int partind = -1, chngind = -1;
for(partind=mid-2; partind>=0; partind--)
{
if(s[partind] < s[partind+1])
break;
}
if(partind < 0)
return "-1";
for(chngind = mid-1; chngind>partind; chngind--)
{
if(s[chngind] > s[partind])
break;
}
// cout<<partind<<" "<<chngind<<endl;
swap(s[chngind] , s[partind]);
reverse(s.begin()+partind+1, s.begin()+mid);
// now s contains the next higher permutation
for(int i = mid + bool(rem); i<n; i++)
s[i] = s[n-1-i]; // mirror right half of the mid
return s;
}//
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while(t--){
string s;
cin >> s;
Solution obj;
cout << obj.nextPalin(s) << endl;
}
return 0;
} // } Driver Code Ends