Valid Parentheses
Total Accepted: 111710
Total Submissions: 375574
Difficulty: Easy
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
Hide Similar Problems
c++ code:
class Solution {
public:
bool isValid(string s) {
stack<char> ss;
for(int i=0;i<s.size();i++) {
if(!ss.empty() && isPair(ss.top(), s[i])) ss.pop();
else ss.push(s[i]);
}
return ss.empty();
}
bool isPair(char left, char right) {
return '['==left && ']'==right || '('==left && ')'==right || '{'==left && '}'==right;
}
};

本文介绍了一个简单的算法,用于判断字符串中的括号是否正确配对。通过使用栈数据结构,算法可以有效地检查包括圆括号、方括号和花括号在内的各种括号是否按正确的顺序关闭。
228

被折叠的 条评论
为什么被折叠?



