Leetcode NO.20 Valid Parentheses

来源:互联网 发布:淘宝机器人在哪里设置 编辑:程序博客网 时间:2024/04/30 04:11

本题题目要求如下:

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.

这题我的思路就是用stack,遇到所有的左括弧,入栈,如果遇到右括弧,则出栈,看看出栈的左括弧是否与右括弧对应。。。

这就是基本想法,剩下的就只是如何实现的问题,就并不算太难了。。。。

class Solution {public:    bool isValid(string s) {        for (int i = 0; i < s.length(); ++i) {            if (parenMap.find(s[i]) != parenMap.end()) {                myStack.push(s[i]);            }            else {                if (myStack.empty() or parenMap[myStack.top()] != s[i]) {                    return false;                }                myStack.pop();            }        }        if (!myStack.empty()) {            return false;        }        return true;    }private:    stack<char> myStack;    unordered_map<char, char> parenMap = {        {'(', ')'},        {'[', ']'},        {'{', '}'}};};


0 0
原创粉丝点击