首页 > 代码库 > 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