首页 > 代码库 > Valid Parentheses
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.
思路:使用栈记录匹配过程。依次遍历s,若当前字符s[i]为‘(‘、‘{‘、‘[‘之一,则将s[i]入栈;否则,取栈顶元素匹配当前字符,若不匹配,返回FALSE,若匹配,继续匹配下一个字符。若s合法,最终栈将为空。
1 class Solution { 2 public: 3 bool isValid( string s ) { 4 stack<char> brackets; 5 for( size_t i = 0; i != s.size(); ++i ) { 6 if( s[i] == ‘(‘ || s[i] == ‘{‘ || s[i] == ‘[‘ ) { 7 brackets.push( s[i] ); 8 } else { 9 if( brackets.empty() || !check( brackets.top(), s[i] ) ) { return false; }10 brackets.pop();11 }12 }13 return brackets.empty();14 }15 private:16 inline bool check( char achar, char si ) {17 return ( achar == ‘(‘ && si == ‘)‘ ) || ( achar == ‘{‘ && si == ‘}‘ ) || ( achar == ‘[‘ && si == ‘]‘ );18 }19 };
Valid Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。