有個(gè)問題是要匹配資格字符串中的左右括號(hào),如(a*(b+c)+d)在位置1和4有左括號(hào),在位置8和11有右括號(hào)。可以觀察到如果從右向左掃描,那么每個(gè)右括號(hào)都與最近遇到的那個(gè)未匹配的左括號(hào)相匹配。現(xiàn)在直接上代碼
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;}}}}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注