LeetCode 20. Valid Parentheses

    xiaoxiao2021-03-25  105

    Valid Parentheses

    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.

    Subscribe to see which companies asked this question.

    Analysis 这道题的题意是判断字符串是否符号匹配。我的做法是利用栈来解决。当碰到‘(’‘[’’{‘时,将这三个符号入栈,而当碰到’)”]”}’时,则将其与栈顶元素匹配。如果不匹配则说明字符串不符合。当退出循环时,如果此时栈不为空也应该返回错误。

    Code

    class Solution { public: bool isValid(string s) { int len = s.size(); stack<char> res; for(int i = 0 ; i < len;++i){ if(s[i]=='(' || s[i]=='[' || s[i]=='{'){ res.push(s[i]); } if(s[i]==')'){ if(res.empty()||res.top() != '(') return false; else res.pop(); } if(s[i]==']'){ if(res.empty()||res.top() != '[') return false; else res.pop(); } if(s[i]=='}'){ if(res.empty()||res.top() != '{') return false; else res.pop(); } } if(!res.empty()) return false; return true; } };
    转载请注明原文地址: https://ju.6miu.com/read-26472.html

    最新回复(0)