1. 程式人生 > >【LeetCode & 劍指offer刷題】字串題11:Valid Parentheses(括號對)

【LeetCode & 劍指offer刷題】字串題11:Valid Parentheses(括號對)

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

Valid Parentheses

Given a string containing just the characters   '(' ,   ')' ,   '{' ,   '}' ,   '['   and   ']'
, determine if the input string is valid. An input string is valid if:
  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]"
Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true
C++   /*問題:有效括號對判斷 #include<stack> 在該環境下已經包含 方法一: 左括號入棧,右括號消解使棧頂元素出棧,若右括號不能與棧頂元素匹配,則返回false */ class Solution {     public :         bool isValid ( string s )         {                         stack < char > stk ;             for ( auto c : s )             {                 switch ( c )                 {                     case '(' :                     case '{' :                     case '[' :                         stk . push ( c ); break ; //左括號入棧                                             case ')' :                         if(stk.empty() || stk.top()!='(' ) //如果棧頂元素為不匹配的括號時,說明不能構成括號對(如example 4)                             return false ;                         else                             stk . pop (); break ; //右括號時原左括號被消解出棧                     case '}' :                         if ( stk . empty () || stk . top ()!= '{' )                             return false ;                         else                             stk . pop (); break ;                     case ']' :                         if ( stk . empty () || stk . top ()!= '[' )                             return false ;                         else                             stk . pop (); break ;                 }             }                         return stk . empty (); //消解完後看棧中是否還有元素,如果還有則為false                     } }; //方法二 /*class Solution {     public:         bool isValid(string s)         {             string left = "([{";             string right = ")]}";             stack<char> stk;                         for(auto c: s)             {                 if(left.find(c) != string::npos) //如果為左括號則入棧                 {                     stk.push(c);                 }                 else //如果為右括號,看棧頂元素是否為左括號                 {                     if(stk.empty() || stk.top()!=left[right.find(c)])                         return false;                     else//匹配消解出棧                         stk.pop();                 }             }                         return stk.empty(); //消解完後看棧中是否還有元素,如果還有則為false                     } };*/