坚持就是一天,又一天。你告诉自己,再坚持一天。
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.
括号匹配,用栈模拟就可以了~
1234567891011121314151617181920212223242526272829303132333435
//C++class Solution {public: bool isValid(string s){ stack<char> ft; for(int i=0;i<(int)s.length();i++){ if(s[i]=='('||s[i]=='['||s[i]=='{') ft.push(s[i]); else{ if(ft.empty()) return false; if(s[i]==')'){ if(ft.top()=='(') ft.pop(); else{ return false; } } else if(s[i]==']'){ if(ft.top()=='[') ft.pop(); else return false; } else if(s[i]=='}'){ if(ft.top()=='{') ft.pop(); else return false; } } } return (int)ft.size()==0; }};