1. 程式人生 > 實用技巧 >LeetCode20. 有效的括號(棧的使用-括號匹配題)

LeetCode20. 有效的括號(棧的使用-括號匹配題)

之前在區塊鏈面試中也遇到過,今天又看到它了,就簡單記錄一下吧。

程式碼如下:

 1 //
 2 // Created by tusxxw on 2020/7/17.
 3 //
 4 /**
 5 給定一個只包括 '(',')','{','}','[',']'的字串,判斷字串是否有效。
 6 
 7 有效字串需滿足:
 8 
 9 左括號必須用相同型別的右括號閉合。
10 左括號必須以正確的順序閉合。
11 注意空字串可被認為是有效字串。
12 
13 示例 1:
14 
15 輸入: "()"
16 輸出: true
17 示例2:
18 
19 輸入: "()[]{}"
20 輸出: true
21 
22
來源:力扣(LeetCode) 23 連結:https://leetcode-cn.com/problems/valid-parentheses 24 著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。 25 */ 26 27 #include <string> 28 #include <iostream> 29 30 using namespace std; 31 32 class Solution { 33 public: 34 bool isValid(string s) { 35 const int len = s.size();
36 int rear = len -1; 37 int stack[len+2];//棧 簡單題自己就陣列模擬棧比STL中的stack要省時間的多 38 int top = 0; 39 for (int i = 0; i < len; ++i) { 40 //如果等於左括號就壓棧 41 if(s[i] == '(' || s[i] == '[' || s[i] == '{') { 42 stack[top++] = s[i];//壓棧 43 }else
if(s[i] == ')') { 44 if(top == 0) return false; 45 if(stack[top-1] == '('){ 46 top--; 47 } else { 48 return false; 49 } 50 }else if(s[i] == ']') { 51 if(top == 0) return false; 52 if(stack[top-1] == '['){ 53 top--; 54 } else { 55 return false; 56 } 57 }else if(s[i] == '}') { 58 if(top == 0) return false; 59 if(stack[top-1] == '{'){ 60 top--; 61 } else { 62 return false; 63 } 64 } 65 } 66 if(top == 0) { 67 return true; 68 }else { 69 return false; 70 } 71 } 72 }; 73 int main(){ 74 Solution s; 75 bool res = s.isValid("()()[]{}"); 76 cout<<res; 77 return 0; 78 }