問題:假設一個算術表達式只有“()","[]","{}",這3種類型的括號,編寫一個算法判斷表達時括號是否匹配,表達式以“\0"結尾。
算法思想:括號匹配是棧的一個典型的應用,當掃描到左括號時,將其入棧,當掃描到右括號時,從棧中彈出一個元素,同時判斷是否匹配(如果棧為空,彈出的元素為空,此時一定不匹配),所以在遍歷表達式的時候不用判斷棧是否為空。按以上思想循環遍歷表達式,如果掃描到"\0”字符時,並且,棧為空,則括號匹配。
代碼如下:
1 bool BracketsCheck(char *str) 2 { 3 InitStack(S); //初始化棧 4 int i=0; 5 while(str[i]!='\0') 6 { 7 switch(str[i]) 8 { //左括號入棧 9 case '(':Push(S,str[i]);break; 10 case '[':Push(S,str[i]);break; 11 case '{':Push(S,str[i]);break; 12 //右括號出棧,並檢查是否匹配 13 case ')':Pop(S,e); 14 if(e!='(') return false; 15 break; 16 17 case ']':Pop(S,e); 18 if(e!='[') return false; 19 break; 20 21 case '}':Pop(S,e); 22 if(e!='{') return false; 23 break; 24 default: 25 break; 26 }//switch 27 i++; //掃描下一個字符 28 }//while 29 if(!IsEmpty(s)) //棧不為空 30 { 31 printf("括號不匹配!\n"); 32 return false; 33 } 34 else 35 { 36 printf("括號匹配!\n"); 37 return true; 38 } 39 }