【python算法】判断字符串/链表是否是回文

一.判断字符串是否为回文

def huiwen(teststring):
    len_s = len(teststring)
    flag = True
    for i in range(len_s//2):
        if teststring[i] != teststring[len_s-1-i]:
            flag = False
            break
    if flag:
        print("是回文")
    else:
        print("不是回文")

二.判断链表是否为回文(简单方法,转换成列表进行比较)

class ListNode:
  def __init__(self, x):
    self.val = x
    self.next = None

class Solution:
  def isPalindrome(self, head):
    """
    :type head: ListNode
    :rtype: bool
    """
    res = []
    cur = head
    while cur:
      res.append(cur.val)
      cur = cur.next
    return res == res[: : -1]


node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3

solution = Solution()
print(solution.isPalindrome(node1))

 

你可能感兴趣的:(算法)