You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true


Solution in C++

class Solution {
public:
    int iAction(char ch) {
        switch(ch) {
            case '(': return 1;
            case '{': return 2;
            case '[': return 3;
            case ')': return -1;
            case '}': return -2;
            case ']': return -3;
        }
        return 0; // no action needed
    }
    bool isValid(string s) {
        stack<char> myStack;
        
        for(int i=0; i<s.length(); i++) {
            int a=iAction(s[i]);
            if (a>0) myStack.push(s[i]);
            else {
                if (myStack.empty()) return false;
                
                int previousCase=iAction(myStack.top());
                if ((int)fabs(a)!=previousCase) return false;
                myStack.pop();
            }
        }
        return (myStack.empty());
        
    }
};


  • No labels