麻烦各位朋友帮忙顶一下增加人气,如有错误或疑问请留言纠正,谢谢
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.
关于堆栈的知识回顾:
#include <stack>
empty() 堆栈为空则返回真
pop() 移除栈顶元素
push() 在栈顶增加元素
size() 返回栈中元素数目
top() 返回栈顶元素
stack<int> a 定义一个堆栈
//vs2012测试代码 #include<iostream> #include<string> #include<stack> using namespace std; class Solution { public: bool isValid(string s) { stack<char> temp; for(int i=0; i<s.length(); i++) { if( !temp.empty() ) { if( temp.top()=='(' && s[i]==')' || temp.top()=='[' && s[i]==']' || temp.top()=='{' && s[i]=='}') temp.pop(); else temp.push(s[i]); } else temp.push(s[i]); } return temp.empty(); } }; int main() { string s; getline( cin , s); //或者cin>>s; Solution lin; cout<<lin.isValid(s)<<endl; return 0; }
//方法一:自测Accepted class Solution { public: bool isValid(string s) { stack<char> temp; for(int i=0; i<s.length(); i++) { if( !temp.empty() ) { if( temp.top()=='(' && s[i]==')' || temp.top()=='[' && s[i]==']' || temp.top()=='{' && s[i]=='}') temp.pop(); else temp.push(s[i]); } else temp.push(s[i]); } return temp.empty(); } };
//方法二:其他人版本 class Solution { public: bool matchBracket(char a, char b) { if(a == '[' && b == ']') return true; if(a == '(' && b == ')') return true; if(a == '{' && b == '}') return true; return false; } bool isValid(string s) { stack<char> charStack; for(int i = 0; i < s.size(); ++i) { if(charStack.empty() || !matchBracket(charStack.top(), s[i])) charStack.push(s[i]); else charStack.pop(); } return charStack.empty(); } };
时间: 2024-11-10 11:35:12