iT邦幫忙

0

我想問問題

c++

When we write a program, the symbols "(" and ")" are used frequently. These two symbols always
appear in pairs. Now, Amy would like to write a program to determine that these two symbols in
a program are legal or not.
The followings are the rules of these two symbols.
One "(" can be canceled by one ")".
Successive "(" or successive ")" cannot be canceled.
The case where ")(" can not be canceled.
Please help Amy to write a program to determine a program is legal or not.

阿鬼啊,請還是說中文吧。
雖然我還是勉強看的懂。

簡單的方式就是直接
算數量是否符合。雖然這招很危險就是了。
我分段翻譯是大該懂題目的意思,不過我對於怎麼寫出程式碼還是有點問題
這就是考驗你的邏輯。這其實還不算是寫程式了。
你可以先說出要怎麼做。再來看要怎麼寫。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
石頭
iT邦研究生 4 級 ‧ 2020-04-07 17:18:12

是不是在說LISP阿? 一堆 ()

石頭 iT邦研究生 4 級 ‧ 2020-04-07 17:21:13 檢舉

我平常是在寫這東西,我也不會特地去找一個檢查()的程式,畢竟自己寫程式還是要知道自己在幹嘛的,有可能你()對了 但是放錯地方也是GG

這因該是對他的考試吧。
因為這可以考邏輯

2
海綿寶寶
iT邦大神 1 級 ‧ 2020-04-07 21:03:01

Google 關鍵字
Uva 673
或是
parentheses balance c++
即可

隨便拿一篇去改
資料來源

//Updated by Anshuman Singh

#include <iostream> //main header file
#include <stack>
using namespace std;

void balance_parentheses();

int main()
{
    int t;
    cout << "Enter number of test cases:";
    cin >> t;

    for (int i = 0; i < t; i++) {
        //calling of function for checking of brackets
        balance_parentheses();
    }

    return 0;
}

void balance_parentheses()
{
    stack<char> a;
    string s;
    cout << "Enter string may or may not containing parentheses:";
    cin >> s;

    int flag = 0; //flag is an arbitrary variable

    for (int i = 0; i < s.length(); i++)
    //for length of the string calculated by number of letters
    {
        if (s[i] == '{' || s[i] == '[' || s[i] == '(') {
            //push function to enter terms in a stack
            a.push(s[i]);
            flag = 1;
        }
        if (!a.empty()) {
            if (s[i] == '}') {
                if (a.top() == '{')
                // top of the stack
                {
                    a.pop();
                    //pop function to delete terms from the top of array
                    continue;
                }
                else
                    break;
            }
            if (s[i] == ']') {
                if (a.top() == '[') {
                    a.pop();
                    continue;
                }
                else
                    break;
            }
            if (s[i] == ')') {
                if (a.top() == '(') {
                    a.pop();
                    continue;
                }
                else
                    break;
            }
        }
        else {
            break;
        }
    }

    if ((a.empty()) && (flag == 1))
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
}

我要發表回答

立即登入回答