码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Parentheses

时间:2014-09-06 16:04:13      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   使用   ar   for   div   

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

标签:style   blog   color   os   io   使用   ar   for   div   

原文地址:http://www.cnblogs.com/moderate-fish/p/3959431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!