有個問題是要匹配資格字符串中的左右括號,如(a*(b+c)+d)在位置1和4有左括號,在位置8和11有右括號??梢杂^察到如果從右向左掃描,那么每個右括號都與最近遇到的那個未匹配的左括號相匹配?,F在直接上代碼
void Match(char* str){stack<int> s;int lengh = strlen(str);for(int i=0;i<lengh;i++){if(str[i]=='(')s.push(i);else if(str[i]==')'){if(!s.empty()){int nLeft = s.top();s.pop();cout<<"right and left is:"<<i<<" "<<nLeft<<endl;}}}}
新聞熱點
疑難解答
圖片精選