7-2 符號配對 (20 分)
阿新 • • 發佈:2018-10-07
sel ini sed double strong alt 輸入格式 相差 def 輸出樣例1:
題目:
請編寫程序檢查C語言源程序中下列符號是否配對:/*
與*/
、(
與)
、[
與]
、{
與}
。
輸入格式:
輸入為一個C語言源程序。當讀到某一行中只有一個句點.
和一個回車的時候,標誌著輸入結束。程序中需要檢查配對的符號不超過100個。
輸出格式:
首先,如果所有符號配對正確,則在第一行中輸出YES
,否則輸出NO
。然後在第二行中指出第一個不配對的符號:如果缺少左符號,則輸出?-右符號
;如果缺少右符號,則輸出左符號-?
。
輸入樣例1:
void test()
{
int i, A[10];
for (i=0; i<10; i++) /*/
A[i] = i;
}
.
輸出樣例1:
NO
/*-?
輸入樣例2:
void test()
{
int i, A[10];
for (i=0; i<10; i++) /**/
A[i] = i;
}]
.
輸出樣例2:
NO
?-]
輸入樣例3:
void test()
{
int i
double A[10];
for (i=0; i<10; i++) /**/
A[i] = 0.1*i;
}
.
輸出樣例3:
YES
思路:
1、首先處理一下輸入,把所有字符串中的左括號與右括號單獨提出來組成一個字符串。這樣後邊如果有錯誤,也好調試找bug。
2、對於‘/*‘和‘*/‘可以分別處理為‘<‘和‘>‘,這兩個尖括號的ASCII碼值相差為2。3、遍歷這個字符串,當碰到左括號的時候就統統壓入棧中,碰到右括號的時候,如果當前的棧是空的就輸出‘NO’,否則就看看是否匹配,不匹配就把棧中的那個括號彈出並說明棧中的那個符號不匹配。
4、很坑的是這個題沒有說明只要有一不匹配就輸出,然後結束就行,最後兩個樣例怎麽都出錯,搜了下答案才知道這麽坑。
代碼:
#include <iostream> #include <cstring> #include <cstdio> #include <string.h> #include <cstdlib> #include <algorithm> #includeView Code<queue> #include <malloc.h> #include <bits/stdc++.h> #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 using namespace std; const int maxn = 1e4+10; typedef long long ll; typedef char SElemType; typedef struct { SElemType* base; SElemType* top; int stacksize; } SqStack; int InitStack(SqStack& S) { S.base = (SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType)); if(!S.base) exit(-2); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return 1; } int GetTop(SqStack S, SElemType& e) { if(S.base == S.top) return 0; e = *(S.top-1); return 1; } int Push(SqStack& S,SElemType e) { if(S.top - S.base >= S.stacksize) { S.base = (SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S.base) exit(-2); S.top = S.base+S.stacksize; S.stacksize += STACKINCREMENT; } *S.top++ = e; return 1; } int Pop(SqStack& S) { if(S.top == S.base) return 0; *S.top,S.top--; return 1; } bool isEmpty(SqStack& S) { if(S.base == S.top) return true; return false; } int main() { SqStack s; InitStack(s); string tmp,str=""; bool ok = false,first = true; while(getline(cin,tmp)) { if(tmp==".")break; for(int i = 0; i<tmp.size(); i++) { if(tmp[i]==‘[‘ || tmp[i]==‘]‘ || tmp[i]==‘{‘ || tmp[i]==‘}‘|| tmp[i]==‘(‘ || tmp[i]==‘)‘) str += tmp[i]; else if(tmp[i]==‘/‘ && tmp[i+1]==‘*‘) { str += "<"; i++; } else if(tmp[i]==‘*‘ && tmp[i+1]==‘/‘) { str += ">"; i++; } } } //cout<<str<<endl; for(int i = 0; i<str.size(); i++) { char op; GetTop(s,op); if(str[i]==‘(‘ || str[i]==‘[‘ ||str[i]==‘{‘ || str[i]==‘<‘) { Push(s,str[i]); continue; } else if(isEmpty(s)) { printf("NO\n"); if(str[i]==‘>‘) printf("?-*/\n"); else printf("?-%c\n",str[i]); ok = true; break; } else if(str[i]-op!=1 && str[i]-op!=2) { printf("NO\n"); if(op==‘<‘) printf("/*-?\n"); else printf("%c-?\n",op); Pop(s); ok = true; i--; break; } else Pop(s); } if(!ok) { if(isEmpty(s)) printf("YES\n"); else { char op; GetTop(s,op); printf("NO\n"); if(op==‘<‘)printf("/*-?\n"); else printf("%c-?\n",op); } } return 0; }
7-2 符號配對 (20 分)