2025年西北工业大学计算机考研复试机试真题
2025年西北工业大学计算机考研复试上机真题
历年西北工业大学计算机考研复试上机真题
历年西北工业大学计算机考研复试机试真题
更多学校题目开源地址:https://gitcode.com/verticallimit1/noobdream
N 诺 DreamJudge 题库:输入 “学校名称” 即可筛选该校历年机试真题,题目均在考纲范围内,按难度自动排序。还可搭配《计算机考研机试攻略》刷题,书中题目可通过题号直接在题库中查找。
括号匹配
题目描述
Time Limit: 1000 ms
Memory Limit: 256 mb
假设表达式中允许包含两种括号:圆括号和方括号。编写一个算法判断表达式中的括号是否正确配对。
输入输出格式
输入描述:
由括号构成的字符串,包含”(“、”)“、”[“和”]“。
输出描述:
如果匹配输出YES,否则输出NO。
输入输出样例
输入样例#:
[([][]())]
输出样例#:
YES
代码一
- #include<bits/stdc++.h>
- using namespace std;
- int main(){
- char x[400];
- scanf("%s",x);
- int k=strlen(x);
- stack<char> s;
- for(int i=0;i<k;i++){
- if(!s.empty()){
- char now=s.top();
- if(now=='['&&x[i]==']'||now=='('&&x[i]==')')
- s.pop();
- else
- s.push(x[i]);
- }
- else{
- s.push(x[i]);
- }
- }
- if(!s.empty())
- cout<<"NO"<<endl;
- else
- cout<<"YES"<<endl;
- return 0;
- }
代码二
- #include <iostream>
- #include <stack>
- #include <unordered_map>
- using namespace std;
- int main() {
- string str;
- cin >> str;
- stack<char> s;
- unordered_map<char, char> mymap = {
- {')', '('},
- {']', '['}
- };
- for (char c : str) {
- if (c == '[' || c == '(') {
- s.push(c);
- } else {
- if (s.empty() || mymap[c] != s.top()) {
- cout << "NO";
- return 0;
- }
- s.pop();
- }
- }
- if (s.empty()) {
- cout << "YES";
- } else {
- cout << "NO";
- }
- return 0;
- }
代码三
- #include<bits/stdc++.h>
- using namespace std;
- string s;
- //字符串只包含
- bool pp(string s){
- //先通过长度判断
- int n=s.size();
- if(n%2!=0) return false;
- stack<char> st;//?位置
- for(int i=0;i<n;i++){
- char c=s[i];
- //不会存在栈满的问题
- if(c=='{'||c=='('||c=='['||c=='<'){
- st.push(c);
- }
- //加一个栈空的条件?
- else if(c=='}'&&st.top()=='{'&& !s.empty()){
- st.pop();
- }
- else if(c==')'&&st.top()=='('&& !s.empty()){
- st.pop();
- }
- else if(c==']'&&st.top()=='['&& !s.empty()){
- st.pop();
- }
- else if(c=='>'&&st.top()=='<'&& !s.empty()){
- st.pop();
- }
- }
- //遍历完检查栈
- return st.empty();
- }
- int main()
- {
- cin>>s;
- if(pp(s)){
- cout<<"YES";
- }
- else{
- cout<<"NO";
- }
- return 0;
- }