首页 > 代码库 > leetcode第20题--Valid Parentheses
leetcode第20题--Valid Parentheses
Problem:
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.
判断输入的括号是不是合法。这题在大二的时候就遇到过了。想不到我的记性这么好。因为当时我什么都不懂,刚学数据结构,然后有个ACMer是助教,他给我讲解了这题。然后我就一直都记得了。也不知道那个师兄现在在哪里牛逼。
回到题目,就是用栈实现。
class Solution { private: char anti(char c) { if (c == ‘]‘) return ‘[‘; if (c == ‘)‘) return ‘(‘; if (c == ‘}‘) return ‘{‘; }public: bool isValid(string s) { int len = s.size(); if (len%2) { return false;} if(s.size() == 0 || s[0] == ‘)‘ || s[0] == ‘]‘ || s[0] == ‘}‘) return false; stack<char> st; for (int i = 0; i < len; i++) { if (s[i] == ‘(‘ || s[i] == ‘{‘ || s[i] == ‘[‘) st.push(s[i]); else if (st.top() == anti(s[i])) st.pop(); else return false; } if (st.empty()) return true; else return false; }};
代码写得有点挫,大概就是这个思路,然后Accept了
leetcode第20题--Valid Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。