第四周Valid Parentheses

来源:互联网 发布:java 时间转时间戳 编辑:程序博客网 时间:2024/06/17 03:25

Valid Parentheses验证括号

Leetcode algorithms problem 20: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.

  • 问题提示

  • 思路

    利用一个栈保存左边的符号,遇到匹配的右符号就将栈顶弹出,最后检测栈是否为空。

代码

class Solution {public:    bool isValid(string s) {        stack<char> brackets;        for(int i = 0; i < s.size(); i++) {            if(s[i] == 40 || s[i] == 91 || s[i] == 123) {                brackets.push(s[i]);            }            else {                if(brackets.size() == 0) {                    return false;                }                char temp = brackets.top();                brackets.pop();                if(s[i] == 41 ) {                    if(temp != 40) {                        return false;                    }                }                else if(s[i] == 93 || s[i] == 125) {                    if(temp != (s[i] - 2)) {                        return false;                    }                }            }        }       return (brackets.size() == 0);    }};

时间复杂度: O(n)
空间复杂度: O(n)


疑难及解决

一开始忘记考虑只有右边括号的情况,导致测试)】}实例时会报runtime error的错误(因为此时栈为空,栈的top及pop函数会出错),折腾了很久才发现,在第一个else部分判断栈是否为空就好了。

原创粉丝点击