20.判断括号的使用是否合法

来源:互联网 发布:域名批量查询软件 编辑:程序博客网 时间:2024/05/21 10:48

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.

知识补充:

1.看到此题立刻想到的就是栈,可以很好的解决类似问题。
2.如果判断语句很多,可以使用switch语句。

栈的使用

#include <stack> stack<int> s1;stack<string> s2;//初始化empty() //堆栈为空则返回真pop() //移除栈顶元素,注意并不返回此元素push() //在栈顶增加元素size() //返回栈中元素数目top() //返回栈顶元素

测试代码(c++):

bool isValid(string s) {        string s1 = "";        for(int i=0;i<s.length();i++)        {            if(s[i]=='('||s[i]=='{'||s[i]=='[')                {                    s1 = s1+s[i];                }            if(s[i]==')'||s[i]=='}'||s[i]==']')                {                    if(s1.back()=='('&&s[i]==')')                    {                        s1.pop_back();                        continue;                    }                    if(s1.back()=='['&&s[i]==']')                    {                        s1.pop_back();                        continue;                    }                    if(s1.back()=='{'&&s[i]=='}')                    {                        s1.pop_back();                        continue;                    }                    return false;                }        }        if(s1.empty())            return true;        else            return false;

性能:

这里写图片描述

参考答案:

class Solution {public:    bool isValid(string s) {    stack <char> paren;        for(char &c :s)        {            switch(c){                case '(':                case '[':                case '{':                    paren.push(c);                    break;                case ')':                    if(paren.empty()||paren.top()!='(') return false;                    else paren.pop();                    break;                case ']':                    if(paren.empty()||paren.top()!='[') return false;                    else paren.pop();break;                    break;                case '}':                    if(paren.empty()||paren.top()!='{') return false;                    else paren.pop();                      break;                default: ;            }        }        return paren.empty();    }};

性能:

这里写图片描述