classSolution2: defisPalindrome(self, x: int) -> bool: if x < 0: returnFalse x = str(x) left, right = 0, len(x) - 1 while left < right: if x[left] != x[right]: returnFalse left += 1 right -= 1 returnTrue
s1 = Solution1() s2 = Solution2() whileTrue: try: x = int(input("An integer please: ")) except ValueError: print("Input is not an integer!") sys.exit() print(s1.isPalindrome(x), s2.isPalindrome(x))
# intLength=3: 1->101 defgetPalindrome(index_of_queries:int)->int: str_half=str(start_from_base+index_of_queries-1) iflen(str_half)>half_of_intLength: return -1 # don't forget to transfer the number to integer returnint(str_half+str_half[-2::-1] if intLength%2==1else str_half+str_half[-1::-1]) for index_of_queries in queries: res.append(getPalindrome(index_of_queries)) return res
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defisPalindrome(self, head: ListNode) -> bool: slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next
# reverse second half pre = None while slow: tmp = slow.next slow.next = pre pre = slow slow = tmp left, right = head, pre while right: if left.val == right.val: left = left.next right = right.next continue else: returnFalse returnTrue
classSolution1: deflongestPalindrome(self, s: str) -> str: res = ""
defexpand(left: int, right: int): while left >= 0and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1:right]
for index inrange(len(s)): tmp_res = expand(index, index) iflen(tmp_res) > len(res): res = tmp_res tmp_res = expand(index, index + 1) iflen(tmp_res) > len(res): res = tmp_res return res