Skip to content

Commit 82b83cd

Browse files
authored
Create next-palindrome-using-same-digits.cpp
1 parent c22bd27 commit 82b83cd

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string nextPalindrome(string num) {
7+
if (!nextPermutation(begin(num), begin(num) + size(num) / 2)) {
8+
return "";
9+
}
10+
copy(begin(num), begin(num) + size(num) / 2, rbegin(num));
11+
return num;
12+
}
13+
14+
private:
15+
template<typename BidiIt>
16+
bool nextPermutation(BidiIt begin, BidiIt end) {
17+
const auto rbegin = reverse_iterator<BidiIt>(end);
18+
const auto rend = reverse_iterator<BidiIt>(begin);
19+
auto pivot = next(rbegin);
20+
while (pivot != rend && *pivot >= *prev(pivot)) {
21+
++pivot;
22+
}
23+
bool is_greater = true;
24+
if (pivot != rend) {
25+
auto change = find_if(rbegin, pivot, bind1st(less<int>(), *pivot));
26+
swap(*change, *pivot);
27+
} else {
28+
is_greater = false;
29+
}
30+
reverse(rbegin, pivot);
31+
return is_greater;
32+
}
33+
};
34+
35+
// Time: O(n)
36+
// Space: O(1)
37+
class Solution2 {
38+
public:
39+
string nextPalindrome(string num) {
40+
if (!next_permutation(begin(num), begin(num) + size(num) / 2)) {
41+
return "";
42+
}
43+
copy(begin(num), begin(num) + size(num) / 2, rbegin(num));
44+
return num;
45+
}
46+
};

0 commit comments

Comments
 (0)