3
Title description:
Given a string, please find out the length of the longest substring that does not contain repeated characters.
Example:
Answer:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:return 0
left = 0
lookup = set()
n = len(s)
max_len = 0
cur_len = 0
for i in range(n):
cur_len += 1
while s[i] in lookup:
lookup.remove(s[left])
left += 1
cur_len -= 1
if cur_len > max_len:max_len = cur_len
lookup.add(s[i])
return max_len
415
Title description:
Given two non-negative integers num1 and num2 in the form of strings, calculate their sum.
answer:
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
ret=''
l1,l2,carry=len(num1)-1,len(num2)-1,0
while l1>=0 or l2 >=0 or carry>0:
if l1>=0:
carry+=int(num1[l1])
l1-=1
if l2>=0:
carry+=int(num2[l2])
l2-=1
ret=str(carry%10)+ret
carry//=10
return ret
1290
Title description:
Give you the head of the reference node of a singly linked list. The value of each node in the linked list is either 0 or 1. It is known that this linked list is a binary representation of an integer number.
Please return the decimal value of the number represented by the linked list.
Example:
Answer:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
res=0
while head:
res=res*2+head.val
head=head.next
return res
1302
Title description:
Give you a binary tree, please return the sum of the leaf nodes with the deepest level.
Example:
Answer:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def deepestLeavesSum(self, root: TreeNode) -> int:
#先把每一层存放到一个列表num中,再把num依次存到res中,最后返回res最后一个列表和
if root==None:
return 0
s=[root]
num=[]
res=[]
while s:
num=[]
for i in s:
num.append(i.val)
res.append(num)
for i in range(len(s)):
node=s.pop(0)
if node.left:
s.append(node.left)
if node.right:
s.append(node.right)
return sum(res[-1])
1315
Title description:
Give you a binary tree, please return the sum of the values of all nodes that meet the following conditions:
the value of the grandparent node of the node is an even number. (The grandparent of a node refers to the parent of the node's parent.)
If there is no node with an even-numbered grandparent, then 0 is returned.
Example:
Answer:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.ans=0
def sumEvenGrandparent(self, root: TreeNode) -> int:
if not root:
return 0
if root.val%2==0:
if root.left:
if root.left.left:
self.ans+=root.left.left.val
if root.left.right:
self.ans+=root.left.right.val
if root.right:
if root.right.left:
self.ans+=root.right.left.val
if root.right.right:
self.ans+=root.right.right.val
self.sumEvenGrandparent(root.left)
self.sumEvenGrandparent(root.right)
return self.ans