贝壳找房秋招Java工程师笔试卷2【2022】
import java.util.*;
public class Main{
static int maxValue = Integer.MIN_VALUE;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int[][][] matrix = new int[row][][];
for(int i = 0; i < row; i++){
int blockNum = sc.nextInt();
matrix[i] = new int[blockNum][2];
for(int j = 0; j < blockNum; j++){
matrix[i][j][0] = sc.nextInt();
matrix[i][j][1] = sc.nextInt();
}
}
int[] colSum = new int[col];
dfs(matrix, colSum, 0, 0);
System.out.println(maxValue);
}
//递归地对每一行的每个块分块填1,当填完最后最后一行的时候更新矩形的最大质量。
private static void dfs(int[][][] matrix, int[] colSum, int row, int blockId) {
if(blockId == matrix[row].length){ // 填完了这一行的block
if(row == matrix.length - 1){ // 到了最第一层 更新每一行的值
int value = 0;
for(int i = 0; i < colSum.length; i++){
value += colSum[i]*colSum[i];
}
maxValue = Math.max(value, maxValue);
} else { // 填下一行的0
dfs(matrix, colSum, row + 1, 0);
}
} else { // 填每一行的每一块的1
for(int j = matrix[row][blockId][0]; j <= matrix[row][blockId][1]; j++){
colSum[j-1]++;
dfs(matrix, colSum, row, blockId + 1);
colSum[j-1]--; // 回溯
}
}
}
}
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n=sc.nextInt();
for(int i=0;i<n;i++){
int m=sc.nextInt();
if(m==0) System.out.println(0);
else if(m==1||m==2) System.out.println(1);
else if(m%2==0)System.out.println(m/2);
else System.out.println((m-1)/2+1);
}
}
}
}
我们只需要在遍历完成后看栈中积压了多少左括号,就表示需要移动多少次前面的右括号到后面来。
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
while(n-- > 0){
int m = sc.nextInt();
String s=sc.next();
char[] str = s.toCharArray();
//char[] str = sc.next().toCharArray();
Stack<Character> stack = new Stack<>();
for(char c: str){
if(c == '('){
stack.push(c);
}else{
if(!stack.isEmpty()) stack.pop();
}
}
System.out.println(stack.size());
}
}
}