第八周leetcode题

来源:互联网 发布:吉利知豆d1续航 编辑:程序博客网 时间:2024/06/13 06:49

Description:

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) {
        stack<char> a;
        
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='('||s[i]=='{'||s[i]=='[') a.push(s[i]);
            
            else if(a.empty()) return 0;
            
            else 
            {
                if(s[i]==')')
                if(a.top()=='(')a.pop();
                else return 0;
                
                
                if(s[i]=='}')
                if(a.top()=='{')a.pop();
                else return 0;
                
                
                if(s[i]==']')
                if(a.top()=='[')a.pop();
                else return 0;
            }
            
           
        }
        
         if(a.empty())return 1;
            else return 0;
    }
};

0 0
原创粉丝点击