Skip to content

Commit 220c9e0

Browse files
committed
Add a solution to Next Palindrome Using Same Digits
1 parent 37bcbee commit 220c9e0

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/next-palindrome-using-same-digits/
3+
* Primary idea: Figure out the first half's next permutation, then double it to the result.
4+
*
5+
* Time Complexity: O(n), Space Complexity: O(1)
6+
*
7+
*/
8+
9+
class NextPalindromeUsingSameDigits {
10+
func nextPalindrome(_ num: String) -> String {
11+
let num = Array(num)
12+
var firstHalf = num[0..<num.count / 2].compactMap { Int(String($0)) }
13+
14+
if num.count <= 1 || !nextPermutation(&firstHalf) {
15+
return ""
16+
}
17+
18+
let firstHalfStr = firstHalf.map { String($0) }.joined()
19+
20+
if num.count % 2 == 0 {
21+
return firstHalfStr + firstHalfStr.reversed()
22+
} else {
23+
return firstHalfStr + String(num[num.count / 2]) + firstHalfStr.reversed()
24+
}
25+
}
26+
27+
private func nextPermutation(_ nums: inout [Int]) -> Bool {
28+
var violateIdx = -1
29+
30+
for i in (1..<nums.count).reversed() {
31+
if nums[i] > nums[i - 1] {
32+
violateIdx = i - 1
33+
break
34+
}
35+
}
36+
37+
if violateIdx == -1 {
38+
nums.reverse()
39+
return false
40+
}
41+
42+
for i in ((violateIdx + 1)..<nums.count).reversed() {
43+
if nums[i] > nums[violateIdx] {
44+
swap(&nums, i, violateIdx)
45+
break
46+
}
47+
}
48+
49+
nums[(violateIdx + 1)...].reverse()
50+
return true
51+
}
52+
53+
private func swap(_ nums: inout [Int], _ l: Int, _ r: Int) {
54+
(nums[l], nums[r]) = (nums[r], nums[l])
55+
}
56+
}

0 commit comments

Comments
 (0)