LeetCode Valid Parentheses

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         char open[] = {'(', '[', '{'};
 5         char close[]= {')', ']', '}'};
 6         
 7         int count[3] = {0, 0, 0};
 8         
 9         vector<char> last_open;
10         int k;
11         for (int i=0; i<s.size(); i++) {
12             char cur = s[i];
13             for (k=0; k<3 && cur != open[k]; k++);
14             if (k < 3) {
15                 count[k]++;
16                 last_open.push_back(open[k]);
17                 continue;
18             }
19             
20             for (k=0; k<3 && cur != close[k]; k++);
21             if (k == 3) continue; // should not be happened
22             if (--count[k] < 0 || open[k] != last_open.back()) {
23                 return false;
24             } else {
25                 last_open.pop_back();
26             }
27         }
28         
29         return (last_open.size() == 0) && !(count[0] | count[1] | count[2]);
30     }
31 };

再水一发!

 

第二轮:

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.

class Solution {
public:
    bool isValid(string s) {
        char pair[256] = {0};
        pair['{'] = '}';
        pair['('] = ')';
        pair['['] = ']';
        stack<char> seq;
        int len = s.size();
        for (int i=0; i<len; i++) {
            char cur = s[i];
            if (cur == '(' || cur == '{' || cur == '[') {
                seq.push(cur);
                continue;
            }
            if (seq.empty()) {
                return false;
            } else {
                if (pair[seq.top()] != cur) {
                    return false;
                }
                seq.pop();
            }
        }
        return seq.empty()
    }
};

不够仔细啊,参考题解:

class Solution {
public:
    bool isValid(string s) {
        char pair[256] = {0};
        pair['{'] = '}';
        pair['('] = ')';
        pair['['] = ']';
        stack<char> seq;
        int len = s.size();
        for (int i=0; i<len; i++) {
            char cur = s[i];
            if (pair[cur] != 0) {
                seq.push(cur);
                continue;
            } else if (seq.empty() || pair[seq.top()] != cur) {
                return false;
            }
            seq.pop();
        }
        return seq.empty();
    }
};

 

posted @ 2014-04-12 10:02  卖程序的小歪  阅读(133)  评论(0编辑  收藏  举报