File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
0564-find-the-closest-palindrome Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ # time complexity: O(n)
2+ # space complexity: O(n)
3+ class Solution :
4+ def nearestPalindromic (self , n : str ) -> str :
5+ lenN = len (n )
6+ i = lenN // 2 - 1 if lenN % 2 == 0 else lenN // 2
7+ firstHalf = int (n [: i + 1 ])
8+ possibilities = []
9+ possibilities .append (
10+ self .halfToPalindrome (firstHalf , lenN % 2 == 0 )
11+ )
12+ possibilities .append (
13+ self .halfToPalindrome (firstHalf + 1 , lenN % 2 == 0 )
14+ )
15+ possibilities .append (
16+ self .halfToPalindrome (firstHalf - 1 , lenN % 2 == 0 )
17+ )
18+ possibilities .append (10 ** (lenN - 1 ) - 1 )
19+ possibilities .append (10 ** lenN + 1 )
20+
21+ diff = float ("inf" )
22+ res = 0
23+ nl = int (n )
24+ for cand in possibilities :
25+ if cand == nl :
26+ continue
27+ if abs (cand - nl ) < diff :
28+ diff = abs (cand - nl )
29+ res = cand
30+ elif abs (cand - nl ) == diff :
31+ res = min (res , cand )
32+ return str (res )
33+
34+ def halfToPalindrome (self , left : int , even : bool ) -> int :
35+ res = left
36+ if not even :
37+ left = left // 10
38+ while left > 0 :
39+ res = res * 10 + left % 10
40+ left //= 10
41+ return res
42+
43+
44+ n = "123"
45+ print (Solution ().nearestPalindromic (n ))
You can’t perform that action at this time.
0 commit comments