Wednesday, January 1, 2014

[LeetCode] Valid Parentheses

Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Analysis:
To find whether parentheses are paired correctly, a stack would be useful.
Scan from the start of string to its end.
When meeting '(','[','{', push them to stack.
When ')', ']', '}' is scanned, find its paired parentheses in the stack.
1) if the stack is empty, return false
2) if the top element in the stack cannot match, i.e. not paired in '(' with ')', '[' with ']' and '{' with '}', return false.
In the end, if the stack is empty, i.e. all parentheses are paired, return true. Other wise return false.



Code is as below.

#include <iostream>
#include <string>
#include <stack>

class Solution {
public:
    bool isValid(std::string s) {
        int n=s.size();
        if(n==0) return true;
        std::stack<char> stack;
        for(int i=0; i<n; i++)
        {
            char c = s[i];
            if(c=='('||c=='['||c=='{')
                stack.push(c);
            else if (c==')'||c==']'||c=='}')
            {
                if(stack.empty()) return false;
                if(c==')'&&stack.top()!='(') return false;
                if(c==']'&&stack.top()!='[') return false;
                if(c=='}'&&stack.top()!='{') return false;
                stack.pop();
            }
        }
        return stack.empty();
    }
};

int main()
{
    bool result;
    Solution s;
    result =  s.isValid("");
    result =  s.isValid("(");
    result =  s.isValid(")");
    result =  s.isValid("()");
    result =  s.isValid("()(");
    result =  s.isValid("())");
    result =  s.isValid("()[]");
    result =  s.isValid("{[()]}");
    result =  s.isValid("([)]");

    return 0;
}

No comments:

Post a Comment