[codility]Brackets

// you can also use includes, for example:
// #include <algorithm>
#include <stack>
int solution(const string &S) {
    // write your code in C++98
    //...using stack to verify if it is properly nested
    stack<char> charStack;
    for(int i = 0; i < S.size(); ++i)
    {
        int curChar = S[i];
        if(curChar == '[' || curChar == '(' || curChar == '{') charStack.push(curChar);
        else
        {
            if(!charStack.empty())
            {
                char topChar = charStack.top();
                if(curChar == '}' && topChar == '{' 
                   || curChar == ']' && topChar == '['
                   || curChar == ')' && topChar == '(')
                    charStack.pop();
                else return 0;
            }
            else return 0;
        }
    }
    //...return result
    if(charStack.empty()) return 1;
    else return 0;
}

你可能感兴趣的:([codility]Brackets)