# 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 while fast and fast.next: slow=slow.next fast=fast.next.next dummy=None while slow: tmp=slow.next slow.next=dummy dummy=slow slow=tmp left=head right=dummy while left and right: if left.val!=right.val: returnFalse left=left.next right=right.next returnTrue
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defsortList(self, head: ListNode) -> ListNode: ifnot head ornot head.next: return head slow=fast=head while fast and fast.next: slow=slow.next fast=fast.next.next center=slow.next slow.next=None
classSolution1: defmergeAlternately(self, word1: str, word2: str) -> str: res = "" length = min(len(word1), len(word2)) for index inrange(length): res += word1[index] + word2[index] res += word1[length:] + word2[length:] return res
classSolution2: defmergeAlternately(self, word1: str, word2: str) -> str: res = "".join(w1 + w2 for w1, w2 inzip(word1, word2)) length_word1 = len(word1) length_word2 = len(word2) if length_word1 > length_word2: res += word1[-(length_word1 - length_word2):] elif length_word1 < length_word2: res += word2[-(length_word2 - length_word1):] else: res = res return res
for i inrange(length_haystack - length_needle + 1): for j inrange(length_needle): if needle[j] != haystack[i + j]: break if j == length_needle - 1: return i return -1