第一题:
这题思路就是一个栈的模板,没有任何东西。。
AC代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int top=-1;//用来只是栈顶的指针
int n1=0;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if (n%2!=0){
System.out.println("No");
return;
}//特判一下,如果是奇数是肯定不可能是配对的
String s=sc.next();
char [] b=new char [105];//栈数组
char [] a=s.toCharArray();
while (n1<n){
if (a[n1]=='('){//如果是(就入栈
top+=1;
b[top]=a[n1];
}
else {//由于题目没有除了)的字符,所以就可以直接出栈了
top-=1;
}
if(top<-1) break;//这里要注意不加有几个数据点过不去,有可能top的值会小于-1,这样就算栈指针越界了
n1++;
}
if (top==-1){//这里就是最后判一下如果top是-1时候,栈就是空栈,完全配对,否者肯定没有完全配对
System.out.println("Yes");
}
else System.out.println("No");
}
}
第二题:后缀表达式 - 洛谷
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#define MAX_AR 50
#define MAX_NUM 50
int main() {
int arr[MAX_NUM]={0};
char ar[MAX_AR]={'0'};
int num=0;
char s;
int s1=0;
while ((s=getchar())!='@'){
if (s=='.'){
arr[num]=s1;
num++;
s1=0;
} else if (s>='0'&&s<='9'){
s1=s1*10+(int)s-'0';
} else {
ar[num]=s;
num++;
}
} //输入处理
int i;
int arr1[50]={0};
int top=-1;
for (i=0;i<num;i++){
if (ar[i]!='+'&&ar[i]!='-'&&ar[i]!='*'&&ar[i]!='/'){
top+=1;
arr1[top]=arr[i];
}
else if (ar[i]=='+'){
arr1[top-1]=arr1[top-1]+arr1[top];
top--;
}
else if (ar[i]=='-'){
arr1[top-1]=arr1[top-1]-arr1[top];
top-=1;
}
else if (ar[i]=='*'){
arr1[top-1]=arr1[top-1]*arr1[top];
top-=1;
}
else if (ar[i]=='/'){
arr1[top-1]=arr1[top-1]/arr1[top];
top-=1;
}
}
printf("%d",arr1[top]);
}