[C++]利用棧實現字符串里的括號匹配


題目:Valid Parentheses

題目來源:leetcode

題目描述:

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

 解題思路:

  1. 建立一個string的棧
  2. 指針指向字符串(下標)
  3. 與棧頂的字符比較,若棧為空直接壓入棧,如和棧頂匹配,則將棧頂彈出,若未匹配,括號直接壓入棧中
  4. 指針向后移一位,回到3,直到字符串被掃描完
  5. 如棧為空,則括號匹配為真,反則為假

全部代碼:

 1 class Solution {
 2 public:
 3     bool isValid(string s) {
 4         bool match(char,char);
 5         stack<char> stk;
 6         for(int i=0;i<s.size();++i)
 7         {
 8             if(stk.size()==0) stk.push(s[i]);
 9             else
10             {
11                 if(match(stk.top(),s[i])) stk.pop();
12                 else stk.push(s[i]);
13             }
14         }
15         if(stk.size()==0) return true;
16         else return false;
17     }
18 };
19 bool match(char f,char l)
20 {
21     switch(f)
22     {
23         case '(': if(l==')') return true;break;
24         case '[': if(l==']') return true;break;
25         case '{': if(l=='}') return true;break;
26      }
27     return false;
28 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM