//Leedcode-Valid Parentheses

来源:互联网 发布:windows 7 编辑:程序博客网 时间:2024/05/22 03:42

题目:

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.

符号匹配。匹配成功返回true,失败返回"true“。申请stack即可解决。代码如下:


class Solution {    public:bool isValid(string s) {        stack<char> c;        //int count = 0;        //char c[100];        int size = s.length();        //int i = 0;        for(int i = 0; i < size; i++) {        char a = s[i];        if(a == '(' || a == '[' || a == '{') {        //c[count] = a;        //count++;        c.push(a);        }        else {        if(c.size() == 0) {        return false;        }                char pre = c.top();        if(a == ')') {        if(pre == '(') {        //count--;        c.pop();        }        else {        return false;        }        }        else if(a == ']') {        if(pre == '[') {        //count--;        c.pop();        }        else {        return false;        }        }        else if(a == '}') {        if(pre == '{') {        //count--;        c.pop();        }        else {        return false;        }        }        }        }        if(c.size() != 0) {        return false;        }        return true;    }};