括號匹配簡易C++實現

 輸入的表達式必須以“$”結尾:

主要是靈活運用棧這個數據結構,代碼如下:

#include <iostream>
using namespace std;

#define MAX_SIZE 100

int kindOf(char c){
 switch(c){
  case '(':return 1;
  case '[':return 2;
  case '{':return 3;
  default:return 0;
 }
}

bool Match(char* array, int length){
 int* stack = new int[MAX_SIZE];
 int top = 0;
 int k = 0;
 for(int i = 0; i < length; i++){
  k = kindOf(array[i]);
  if(k){
   stack[top++] = k;
  }else if(array[i] == ')'){
   top--;
   if(top >= 0 && stack[top] != 1){
    cout<<"Failed!"<<endl;
    return false;
   }
  }else if(array[i] == ']'){
   top--;
   if(top >= 0 && stack[top] != 2){
    cout<<"Failed!"<<endl;
    return false;
   }
  }else if(array[i] == '}'){
   top--;
   if(top >= 0 && stack[top] != 3){
    cout<<"Failed!"<<endl;
    return false;
   }
  }
 }
 if(top == 0){
  cout<<"Successed!"<<endl;
  return true;
 }else{
  cout<<"Failed!"<<endl;
  return false;
 }
}

void main(){
 char array[MAX_SIZE];
 int length = 0;
 cout<<"chs:";
 for(int i = 0; i < MAX_SIZE; i++){
  char c;
  cin>>c;
  if(c == '$')//'$'爲終結符
   break;
  array[i] = c;
  length++;
 }
 Match(array,length);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章