力扣 python刷题

1.两数之和

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        directory=dict()
        for i,x in enumerate(nums):
            if target-x in directory:
                return [i,directory[target-x]]
            directory[x]=i

2.两数相加

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head=ListNode(0)
        carry=0
        iter=head
        while l1 or l2:
            num1=l1.val if l1 else 0
            num2=l2.val if l2 else 0
            tmp=num1+num2+carry
            carry=1 if tmp>=10 else 0
            head.next=ListNode(tem%10)
            head=head.next
            l1=l1.next if l1 else None
            l2=l2.next if l2 else None
        head.next=ListNode(1) if carry else None
        return iter.next

or

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        carry = 0
        iter = head
        while True:
            tmp = (l1.val if l1 else 0) + (l2.val if l2 else 0) + carry
            stopNum = tmp % 10
            carry = tmp / 10
            iter.val = stopNum
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
            if not l1 and not l2 and carry == 0:
                break
            else:
                nextNode = ListNode(0)
                iter.next = nextNode
                iter = nextNode
        return head

3.无重复字符的最大子串

滑窗

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        directory={}
        length=0
        start=0
        for i in range(len(s)):
            if s[i] in directory and start <= directory[s[i]]:
                start = directory[s[i]] +1
            length =max(length,i-start+1)
            directory[s[i]] = i
        return length

用index查找

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s: return 0
        maxlength = 0
        sub = ''
        for i in range(len(s)):
            if s[i] not in sub:
                sub += s[i]
            else:
                idx = sub.index(s[i])
                sub = sub[idx+1:] + s[i]
            maxlength = max(maxlength, len(sub))
        return maxlength

4.

5.

你可能感兴趣的:(力扣,LeetCode,Python)