Leetcode——20. Valid Parentheses

来源:互联网 发布:linux shell usleep 编辑:程序博客网 时间:2024/06/07 15:18

1. 概述

1.1 题目

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 解题思路

这道题是需要判断是否匹配,也就是在一对括号中的括号也是配对的,若为空也算是配对成功。因而从字符串的左边看的话,可以看做是一个堆栈,遇到一个左括号,就进栈;再遇到一个右括号就判断与栈顶的括号是不是配对的,若是配对就弹出去。直到走完整个字符串。最后返回栈是否为空。

2.  编码

class Solution {public:    bool isValid(string s) {        int len(s.length());    //求出字符串的长度        if(0 == len) return true;        if(len % 2 == 1) return false;  //长度是奇数的情况                if(2 == len)    //两个字符的情况        {            char kk = s.at(1) - s.at(0);            if(kk==1 || kk==2)  return true;            else return false;        }        stack<char> m_stack;        for(int i=0; i<len; ++i)        {            if(m_stack.size() == 0)                m_stack.push(s.at(i));            else            {                char kk = m_stack.top();    //取顶部元素                kk = s.at(i) - kk;                if(!(kk==1 || kk==2))                    m_stack.push(s.at(i));                else                    m_stack.pop();            }        }        return m_stack.empty();    }};


原创粉丝点击