實驗二 括弧匹配判斷演算法

來源:互聯網
上載者:User

題目連結<http://acm.zjnu.edu.cn/DataStruct/showproblem?problem_id=1002>

實驗二 括弧匹配判斷演算法

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 2202   Accepted: 924

Description

假設在運算式中([]())或[([ ][ ])]等為正確的格式,[( ])或([( ))或 (( )])均為不正確的格式。基於棧設計一個判斷括弧是否正確匹配的演算法。

Input

輸入資料有多組,每組測試資料一行,一個字串,只包含 ‘[‘ ,’]’ ,’(‘ ,‘)’ 。

Output

對於每組測試資料,若括弧匹配輸出yes,否則輸出 no。

Sample Input []()[] ([[]])[)

Sample Output yes no

題解:

利用stack判斷儲存。從頭到尾掃描一遍字串,如果是左括弧(無論是小的還是中的)都入棧。如果是右括弧,就把當前的字元與棧的頭元素比對,如果配對就棧跳出頭元素,如果不配對,那麼就可以把標記的flag設為0。如果是右括弧,且棧內沒有元素,則flag也可為0。如果掃描已經完畢,棧內仍然存在元素,那麼flag也是0。

oj的原因多組輸入不能用~scanf("")


#include <iostream>#include <stdio.h>#include <map>#include <queue>#include <string.h>#include <string>#include <stack>using namespace std;typedef long long LL;int main(){    char s[10005];    stack<char>st;    while(scanf("%s",s)!=EOF){        while(!st.empty()) st.pop();        int len=strlen(s),flag=1;        for(int i=0;i<len;i++){            if(s[i]=='('||s[i]=='[')                st.push(s[i]);            else{                if(st.empty()){                    flag=0;break;                }                char tmp=st.top();                st.pop();                if(s[i]==')'&&tmp=='['){                    flag=0;                    break;                }                else if(s[i]==']'&&tmp=='('){                    flag=0;                    break;                }            }        }        if(!st.empty()) flag=0;        if(flag) printf("yes\n");        else printf("no\n");    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.