classSolution{public:intmaximalSquare(vector<vector<char>>& matrix){if(matrix.empty()|| matrix[0].empty())return0;int n = matrix.size(), m = matrix[0].size();
vector<vector<int>>f(n +1, vector<int>(m +1));int res =0;for(int i =1; i <= n; i ++)for(int j =1; j <= m; j ++)if(matrix[i -1][j -1]=='1'){
f[i][j]=min(f[i -1][j],min(f[i][j -1], f[i -1][j -1]))+1;
res =max(res, f[i][j]);}return res * res;}};
funcmaximalSquare(matrix [][]byte)int{
dp :=make([][]int,len(matrix))
maxSide :=0for i :=0; i <len(matrix); i++{
dp[i]=make([]int,len(matrix[i]))for j :=0; j <len(matrix[i]); j++{
dp[i][j]=int(matrix[i][j]-'0')if dp[i][j]==1{
maxSide =1}}}for i :=1; i <len(matrix); i++{for j :=1; j <len(matrix[i]); j++{if dp[i][j]==1{
dp[i][j]=min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1])+1if dp[i][j]> maxSide {
maxSide = dp[i][j]}}}}return maxSide * maxSide
}funcmin(x, y int)int{if x < y {return x
}return y
}
第二百二十二题:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/classSolution{public:intcountNodes(TreeNode* root){if(!root)return0;auto l = root->left, r = root->right;int x =1, y =1;while(l) l = l->left, x ++;while(r) r = r->right, y ++;if(x == y)return(1<< x)-1;returncountNodes(root->left)+1+countNodes(root->right);}};
typedeflonglong LL;classSolution{public:intcomputeArea(LL A, LL B, LL C, LL D, LL E, LL F, LL G, LL H){
LL X =max(0ll,min(C, G)-max(A, E));
LL Y =max(0ll,min(D, H)-max(B, F));return(C - A)*(D - B)+(G - E)*(H - F)- X * Y;}};
publicintcomputeArea(int A,int B,int C,int D,int E,int F,int G,int H){long X = Math.max(0,(long)Math.min(G, C)- Math.max(A, E));long Y = Math.max(0,(long)Math.min(D, H)- Math.max(B, F));return(int)((long)(C - A)*(D - B)- X * Y +(G - E)*(H - F));}
classSolution:defcomputeArea(self, A:int, B:int, C:int, D:int, E:int, F:int, G:int, H:int)->int:# 调整两个矩形位置, 让第一个矩形靠最左边if A > E:return self.computeArea(E, F, G, H, A, B, C, D)# 没有重叠的情况if B >= H or D <= F or C <= E:returnabs(A - C)*abs(B - D)+abs(E - G)*abs(F - H)# 重叠情况# 下边界
down =max(A, E)# 上
up =min(C, G)# 左
left =max(B, F)# 右
right =min(D, H)returnabs(A - C)*abs(B - D)+abs(E - G)*abs(F - H)-abs(up - down)*abs(left - right)
funccomputeArea(A int, B int, C int, D int, E int, F int, G int, H int)int{// 取 cg 的小值 减 ae 的大值 得到 边长
w :=min(C,G)-max(A,E)// 同理// 取 dh 的小值 减 bf 的大值 得到 高度
h :=min(D,H)-max(B,F)// 面值等于 s1+s2-重叠部分// 这里做下优化 避免溢出 写成 s1-重叠部分+s2// 上面算出来的w和h 有可能出现负数// 出现负数那就是没有重叠的部分了 置为0 去乘面积就好了 , 那就等于s1+s2 return(C-A)*(D-B)-max(w,0)*max(h,0)+(G-E)*(H-F)}funcmin(x,y int)int{if x>y{return y
}return x
}funcmax(x,y int)int{if x>y{return x
}return y
}
第二百二十四题:
classSolution{public:voideval(stack<int>& num, stack<char>& op){auto b = num.top(); num.pop();auto a = num.top(); num.pop();auto c = op.top(); op.pop();int r;if(c =='+') r = a + b;else r = a - b;
num.push(r);}intcalculate(string s){
stack<int> num;
stack<char> op;for(int i =0; i < s.size(); i ++){auto c = s[i];if(c ==' ')continue;if(isdigit(c)){int x =0, j = i;while(j < s.size()&&isdigit(s[j])) x = x *10+(s[j ++]-'0');
i = j -1;
num.push(x);}elseif(c =='(') op.push(c);elseif(c ==')'){while(op.top()!='(')eval(num, op);
op.pop();}else{while(op.size()&& op.top()!='(')eval(num, op);
op.push(c);}}while(op.size())eval(num, op);return num.top();}};
classSolution{publicintcalculate(String s){
Stack<Integer> stack =newStack<Integer>();int operand =0;int result =0;// For the on-going resultint sign =1;// 1 means positive, -1 means negativefor(int i =0; i < s.length(); i++){char ch = s.charAt(i);if(Character.isDigit(ch)){// Forming operand, since it could be more than one digit
operand =10* operand +(int)(ch -'0');}elseif(ch =='+'){// Evaluate the expression to the left,// with result, sign, operand
result += sign * operand;// Save the recently encountered '+' sign
sign =1;// Reset operand
operand =0;}elseif(ch =='-'){
result += sign * operand;
sign =-1;
operand =0;}elseif(ch =='('){// Push the result and sign on to the stack, for later// We push the result first, then sign
stack.push(result);
stack.push(sign);// Reset operand and result, as if new evaluation begins for the new sub-expression
sign =1;
result =0;}elseif(ch ==')'){// Evaluate the expression to the left// with result, sign and operand
result += sign * operand;// ')' marks end of expression within a set of parenthesis// Its result is multiplied with sign on top of stack// as stack.pop() is the sign before the parenthesis
result *= stack.pop();// Then add to the next operand on the top.// as stack.pop() is the result calculated before this parenthesis// (operand on stack) + (sign on stack * (result from parenthesis))
result += stack.pop();// Reset the operand
operand =0;}}return result +(sign * operand);}}
classSolution:defcalculate(self, s:str)->int:
stack =[]
operand =0
res =0# For the on-going result
sign =1# 1 means positive, -1 means negative for ch in s:if ch.isdigit():# Forming operand, since it could be more than one digit
operand =(operand *10)+int(ch)elif ch =='+':# Evaluate the expression to the left,# with result, sign, operand
res += sign * operand
# Save the recently encountered '+' sign
sign =1# Reset operand
operand =0elif ch =='-':
res += sign * operand
sign =-1
operand =0elif ch =='(':# Push the result and sign on to the stack, for later# We push the result first, then sign
stack.append(res)
stack.append(sign)# Reset operand and result, as if new evaluation begins for the new sub-expression
sign =1
res =0elif ch ==')':# Evaluate the expression to the left# with result, sign and operand
res += sign * operand
# ')' marks end of expression within a set of parenthesis# Its result is multiplied with sign on top of stack# as stack.pop() is the sign before the parenthesis
res *= stack.pop()# stack pop 1, sign# Then add to the next operand on the top.# as stack.pop() is the result calculated before this parenthesis# (operand on stack) + (sign on stack * (result from parenthesis))
res += stack.pop()# stack pop 2, operand# Reset the operand
operand =0return res + sign * operand
classMyStack{public:/** Initialize your data structure here. */
queue<int> q, w;MyStack(){}/** Push element x onto stack. */voidpush(int x){
q.push(x);}/** Removes the element on top of the stack and returns that element. */intpop(){while(q.size()>1) w.push(q.front()), q.pop();int t = q.front();
q.pop();while(w.size()) q.push(w.front()), w.pop();return t;}/** Get the top element. */inttop(){while(q.size()>1) w.push(q.front()), q.pop();int t = q.front();
q.pop();while(w.size()) q.push(w.front()), w.pop();
q.push(t);return t;}/** Returns whether the stack is empty. */boolempty(){return q.empty();}};/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
classMyStack{
Queue<Integer> queue;/** Initialize your data structure here. */publicMyStack(){
queue =newLinkedList<Integer>();}/** Push element x onto stack. */publicvoidpush(int x){int n = queue.size();
queue.offer(x);for(int i =0; i < n; i++){
queue.offer(queue.poll());}}/** Removes the element on top of the stack and returns that element. */publicintpop(){return queue.poll();}/** Get the top element. */publicinttop(){return queue.peek();}/** Returns whether the stack is empty. */publicbooleanempty(){return queue.isEmpty();}}
classMyStack:def__init__(self):"""
Initialize your data structure here.
"""
self.queue = collections.deque()defpush(self, x:int)->None:"""
Push element x onto stack.
"""
n =len(self.queue)
self.queue.append(x)for _ inrange(n):
self.queue.append(self.queue.popleft())defpop(self)->int:"""
Removes the element on top of the stack and returns that element.
"""return self.queue.popleft()deftop(self)->int:"""
Get the top element.
"""return self.queue[0]defempty(self)->bool:"""
Returns whether the stack is empty.
"""returnnot self.queue
type MyStack struct{
queue []int}/** Initialize your data structure here. */funcConstructor()(s MyStack){return}/** Push element x onto stack. */func(s *MyStack)Push(x int){
n :=len(s.queue)
s.queue =append(s.queue, x)for; n >0; n--{
s.queue =append(s.queue, s.queue[0])
s.queue = s.queue[1:]}}/** Removes the element on top of the stack and returns that element. */func(s *MyStack)Pop()int{
v := s.queue[0]
s.queue = s.queue[1:]return v
}/** Get the top element. */func(s *MyStack)Top()int{return s.queue[0]}/** Returns whether the stack is empty. */func(s *MyStack)Empty()bool{returnlen(s.queue)==0}
第二百二十六题:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/classSolution{public:
TreeNode*invertTree(TreeNode* root){if(!root)returnNULL;swap(root->left, root->right);invertTree(root->left);invertTree(root->right);return root;}};
classSolution{public TreeNode invertTree(TreeNode root){if(root == null){return null;}
TreeNode left =invertTree(root.left);
TreeNode right =invertTree(root.right);
root.left = right;
root.right = left;return root;}}
classSolution:definvertTree(self, root: TreeNode)-> TreeNode:ifnot root:return root
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.left, root.right = right, left
return root
funcinvertTree(root *TreeNode)*TreeNode {if root ==nil{returnnil}
left :=invertTree(root.Left)
right :=invertTree(root.Right)
root.Left = right
root.Right = left
return root
}
第二百二十七题:
classSolution{public:
stack<int> num;
stack<char> op;voideval(){int b = num.top(); num.pop();int a = num.top(); num.pop();char c = op.top(); op.pop();int r;if(c =='+') r = a + b;elseif(c =='-') r = a - b;elseif(c =='*') r = a * b;else r = a / b;
num.push(r);}intcalculate(string s){
unordered_map<char,int> pr;
pr['+']= pr['-']=1, pr['*']= pr['/']=2;for(int i =0; i < s.size(); i ++){char c = s[i];if(c ==' ')continue;if(isdigit(c)){int x =0, j = i;while(j < s.size()&&isdigit(s[j])) x = x *10+(s[j ++]-'0');
num.push(x);
i = j -1;}else{while(op.size()&& pr[op.top()]>= pr[c])eval();
op.push(c);}}while(op.size())eval();return num.top();}};
classSolution{publicintcalculate(String s){
Stack<Integer> numStack =newStack<>();char lastOp ='+';char[] arr = s.toCharArray();for(int i =0; i < arr.length; i ++){if(arr[i]==' ')continue;if(Character.isDigit(arr[i])){int tempNum = arr[i]-'0';while(++i < arr.length && Character.isDigit(arr[i])){
tempNum = tempNum *10+(arr[i]-'0');} i--;if(lastOp =='+') numStack.push(tempNum);elseif(lastOp =='-') numStack.push(-tempNum);else numStack.push(res(lastOp, numStack.pop(), tempNum));}else lastOp = arr[i];}int ans =0;for(int num : numStack) ans += num;return ans;}privateintres(char op,int a,int b){if(op =='*')return a * b;elseif(op =='/')return a / b;elseif(op =='+')return a + b;//其实加减运算可以忽略elsereturn a - b;}}
classSolution:defcalculate(self, s:str)->int:
stack =[]
num =0; sign ='+'for i inrange(len(s)):if s[i].isdigit():
num = num*10+int(s[i])if s[i]in'+-*/'or i ==len(s)-1:if sign =='+':
stack.append(num)elif sign =='-':
stack.append(-num)elif sign =='*':
stack.append(stack.pop()* num)else:
stack.append(int(stack.pop()/ num))
num =0; sign = s[i]returnsum(stack)
funccalculate(s string)int{
stack :=make([]int,0,len(s))
op :=make([]int,0,len(s))
num :=0for i:=0; i<len(s); i++{switch s[i]{case'1','2','3','4','5','6','7','8','9','0':
num =0for i <len(s)&& s[i]>='0'&&s[i]<='9'{
num = num*10+int(s[i]-'0')
i++}iflen(op)>0&& op[len(op)-1]>2{if op[len(op)-1]==3{
stack[len(stack)-1]*= num
}else{
stack[len(stack)-1]/= num
}
op = op[:len(op)-1]}else{
stack =append(stack, num)}// 退一格i 上面自动i++
i--case'+':
op =append(op,1)case'-':
op =append(op,-1)case'*':
op =append(op,3)case'/':
op =append(op,4)default:// fmt.Println(s[i])}}// fmt.Println(stack, op)forlen(op)>0{
stack[1]= stack[0]+ op[0]*stack[1]
op = op[1:]
stack = stack[1:]}return stack[0]}
第二百二十一题:class Solution {public: int maximalSquare(vector<vector<char>>& matrix) { if (matrix.empty() || matrix[0].empty()) return 0; int n = matrix.size(), m = matrix[0].size(); vector<vector<int>>